Search in sources :

Example 6 with CommandExecutionException

use of net.aufdemrand.denizencore.exceptions.CommandExecutionException in project Denizen-For-Bukkit by DenizenScript.

the class ShootCommand method execute.

@SuppressWarnings("unchecked")
@Override
public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
    dEntity originEntity = (dEntity) scriptEntry.getObject("originEntity");
    dLocation originLocation = scriptEntry.hasObject("originLocation") ? (dLocation) scriptEntry.getObject("originLocation") : new dLocation(originEntity.getEyeLocation().add(originEntity.getEyeLocation().getDirection()));
    boolean no_rotate = scriptEntry.hasObject("no_rotate") && scriptEntry.getElement("no_rotate").asBoolean();
    // If there is no destination set, but there is a shooter, get a point
    // in front of the shooter and set it as the destination
    final dLocation destination = scriptEntry.hasObject("destination") ? (dLocation) scriptEntry.getObject("destination") : (originEntity != null ? new dLocation(originEntity.getEyeLocation().clone().add(originEntity.getEyeLocation().clone().getDirection().multiply(30))) : (originLocation != null ? new dLocation(originLocation.clone().add(originLocation.getDirection().multiply(30))) : null));
    // TODO: Same as PUSH -- is this the place to do this?
    if (destination == null) {
        dB.report(scriptEntry, getName(), "No destination specified!");
        return;
    }
    final List<dEntity> entities = (List<dEntity>) scriptEntry.getObject("entities");
    final dScript script = (dScript) scriptEntry.getObject("script");
    final dList definitions = (dList) scriptEntry.getObject("definitions");
    dEntity shooter = (dEntity) scriptEntry.getObject("shooter");
    Element height = scriptEntry.getElement("height");
    Element gravity = scriptEntry.getElement("gravity");
    Element speed = scriptEntry.getElement("speed");
    Element spread = scriptEntry.getElement("spread");
    dLocation lead = (dLocation) scriptEntry.getObject("lead");
    // Report to dB
    dB.report(scriptEntry, getName(), aH.debugObj("origin", originEntity != null ? originEntity : originLocation) + aH.debugObj("entities", entities.toString()) + destination.debug() + height.debug() + (gravity != null ? gravity.debug() : "") + (speed != null ? speed.debug() : "") + (script != null ? script.debug() : "") + (shooter != null ? shooter.debug() : "") + (spread != null ? spread.debug() : "") + (lead != null ? lead.debug() : "") + (no_rotate ? aH.debugObj("no_rotate", "true") : "") + (definitions != null ? definitions.debug() : ""));
    // Keep a dList of entities that can be called using <entry[name].shot_entities>
    // later in the script queue
    final dList entityList = new dList();
    // Go through all the entities, spawning/teleporting and rotating them
    for (dEntity entity : entities) {
        if (!entity.isSpawned() || !no_rotate) {
            entity.spawnAt(originLocation);
        }
        // Only add to entityList after the entities have been
        // spawned, otherwise you'll get something like "e@skeleton"
        // instead of "e@57" on it
        entityList.add(entity.toString());
        if (!no_rotate) {
            NMSHandler.getInstance().getEntityHelper().faceLocation(entity.getBukkitEntity(), destination);
        }
        // when applicable
        if (entity.isProjectile() && (shooter != null || originEntity != null)) {
            entity.setShooter(shooter != null ? shooter : originEntity);
            // Also, watch for it hitting a target
            arrows.put(entity.getUUID(), null);
        }
    }
    // Add entities to context so that the specific entities created/spawned
    // can be fetched.
    scriptEntry.addObject("shot_entities", entityList);
    if (spread == null) {
        Position.mount(Conversion.convertEntities(entities));
    }
    // Get the entity at the bottom of the entity list, because
    // only its gravity should be affected and tracked considering
    // that the other entities will be mounted on it
    final dEntity lastEntity = entities.get(entities.size() - 1);
    if (gravity == null) {
        gravity = new Element(lastEntity.getEntityType().getGravity());
    }
    if (speed == null) {
        Vector v1 = lastEntity.getLocation().toVector();
        Vector v2 = destination.toVector();
        Vector v3 = Velocity.calculate(v1, v2, gravity.asDouble(), height.asDouble());
        lastEntity.setVelocity(v3);
    } else if (lead == null) {
        Vector relative = destination.clone().subtract(originLocation).toVector();
        lastEntity.setVelocity(relative.normalize().multiply(speed.asDouble()));
    } else {
        double g = 20;
        double v = speed.asDouble();
        Vector relative = destination.clone().subtract(originLocation).toVector();
        double testAng = Velocity.launchAngle(originLocation, destination.toVector(), v, relative.getY(), g);
        double hangTime = Velocity.hangtime(testAng, v, relative.getY(), g);
        Vector to = destination.clone().add(lead.clone().multiply(hangTime)).toVector();
        relative = to.clone().subtract(originLocation.toVector());
        Double dist = Math.sqrt(relative.getX() * relative.getX() + relative.getZ() * relative.getZ());
        if (dist == 0) {
            dist = 0.1d;
        }
        testAng = Velocity.launchAngle(originLocation, to, v, relative.getY(), g);
        relative.setY(Math.tan(testAng) * dist);
        relative = relative.normalize();
        v = v + (1.188 * Math.pow(hangTime, 2));
        relative = relative.multiply(v / 20.0d);
        lastEntity.setVelocity(relative);
    }
    if (spread != null) {
        Vector base = lastEntity.getVelocity().clone();
        float sf = spread.asFloat();
        for (dEntity entity : entities) {
            Vector newvel = Velocity.spread(base, (CoreUtilities.getRandom().nextDouble() > 0.5f ? 1 : -1) * Math.toRadians(CoreUtilities.getRandom().nextDouble() * sf), (CoreUtilities.getRandom().nextDouble() > 0.5f ? 1 : -1) * Math.toRadians(CoreUtilities.getRandom().nextDouble() * sf));
            entity.setVelocity(newvel);
        }
    }
    final dLocation start = new dLocation(lastEntity.getLocation());
    final Vector start_vel = lastEntity.getVelocity();
    // A task used to trigger a script if the entity is no longer
    // being shot, when the script argument is used
    BukkitRunnable task = new BukkitRunnable() {

        boolean flying = true;

        dLocation lastLocation = null;

        Vector lastVelocity = null;

        public void run() {
            // If the entity is no longer spawned, stop the task
            if (!lastEntity.isSpawned()) {
                flying = false;
            } else // the air, stop the task
            if (lastVelocity != null) {
                if (lastVelocity.distance(lastEntity.getBukkitEntity().getVelocity()) < 0.05) {
                    flying = false;
                }
            }
            // are met
            if (!flying) {
                this.cancel();
                if (script != null) {
                    if (lastLocation == null) {
                        lastLocation = start;
                    }
                    if (lastVelocity == null) {
                        lastVelocity = start_vel;
                    }
                    // Build a queue out of the targeted script
                    List<ScriptEntry> entries = script.getContainer().getBaseEntries(scriptEntry.entryData.clone());
                    ScriptQueue queue = InstantQueue.getQueue(ScriptQueue.getNextId(script.getContainer().getName())).addEntries(entries);
                    // Add relevant definitions
                    queue.addDefinition("location", lastLocation.identify());
                    queue.addDefinition("shot_entities", entityList.toString());
                    queue.addDefinition("last_entity", lastEntity.identify());
                    // Handle hit_entities definition
                    dList hitEntities = new dList();
                    for (dEntity entity : entities) {
                        if (arrows.containsKey(entity.getUUID())) {
                            dEntity hit = arrows.get(entity.getUUID());
                            arrows.remove(entity.getUUID());
                            if (hit != null) {
                                hitEntities.add(hit.identify());
                            }
                        }
                    }
                    queue.addDefinition("hit_entities", hitEntities.identify());
                    if (definitions != null) {
                        int x = 1;
                        String[] definition_names = null;
                        try {
                            definition_names = script.getContainer().getString("definitions").split("\\|");
                        } catch (Exception e) {
                        // TODO: less lazy handling
                        }
                        for (String definition : definitions) {
                            String name = definition_names != null && definition_names.length >= x ? definition_names[x - 1].trim() : String.valueOf(x);
                            queue.addDefinition(name, definition);
                            dB.echoDebug(scriptEntry, "Adding definition %" + name + "% as " + definition);
                            x++;
                        }
                    }
                    // Start it!
                    queue.start();
                }
                scriptEntry.setFinished(true);
            } else {
                // Record it's position in case the entity dies
                lastLocation = lastEntity.getLocation();
                lastVelocity = lastEntity.getVelocity();
            }
        }
    };
    task.runTaskTimer(DenizenAPI.getCurrentInstance(), 0, 2);
}
Also used : net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList) Element(net.aufdemrand.denizencore.objects.Element) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) ScriptEntry(net.aufdemrand.denizencore.scripts.ScriptEntry) InvalidArgumentsException(net.aufdemrand.denizencore.exceptions.InvalidArgumentsException) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException) net.aufdemrand.denizen.objects.dEntity(net.aufdemrand.denizen.objects.dEntity) net.aufdemrand.denizencore.objects.dScript(net.aufdemrand.denizencore.objects.dScript) net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList) List(java.util.List) net.aufdemrand.denizen.objects.dLocation(net.aufdemrand.denizen.objects.dLocation) Vector(org.bukkit.util.Vector) ScriptQueue(net.aufdemrand.denizencore.scripts.queues.ScriptQueue)

Example 7 with CommandExecutionException

use of net.aufdemrand.denizencore.exceptions.CommandExecutionException 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 8 with CommandExecutionException

use of net.aufdemrand.denizencore.exceptions.CommandExecutionException in project Denizen-For-Bukkit by DenizenScript.

the class ZapCommand method execute.

@Override
public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
    final dScript script = (dScript) scriptEntry.getObject("script");
    Duration duration = (Duration) scriptEntry.getObject("duration");
    dB.report(scriptEntry, getName(), ((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().debug() + script.debug() + (scriptEntry.hasObject("step") ? scriptEntry.getElement("step").debug() : aH.debugObj("step", "++ (inc)")) + (duration != null ? duration.debug() : ""));
    String step = scriptEntry.hasObject("step") ? scriptEntry.getElement("step").asString() : null;
    // Let's get the current step for reference.
    String currentStep = InteractScriptHelper.getCurrentStep(((BukkitScriptEntryData) scriptEntry.entryData).getPlayer(), script.getName());
    // Special-case for backwards compatibility: ability to use ZAP to count up steps.
    if (step == null) {
        // to '1' so it can be incremented next time.
        if (aH.matchesInteger(currentStep)) {
            step = String.valueOf(aH.getIntegerFrom(currentStep) + 1);
        } else {
            step = "1";
        }
    }
    if (step.equalsIgnoreCase(currentStep)) {
        dB.echoError(scriptEntry.getResidingQueue(), "Zapping to own current step!");
        return;
    }
    // ZAP for this script is taking place.
    if (durations.containsKey(((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().getSaveName() + "," + script.getName())) {
        try {
            DenizenAPI.getCurrentInstance().getServer().getScheduler().cancelTask(durations.get(((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().getSaveName() + "," + script.getName()));
        } catch (Exception e) {
        }
    }
    // One last thing... check for duration.
    if (duration != null && duration.getSeconds() > 0) {
        // If a DURATION is specified, the currentStep should be remembered and
        // restored after the duration.
        scriptEntry.addObject("step", new Element(currentStep));
        // And let's take away the duration that was set to avoid a re-duration
        // inception-ion-ion-ion-ion... ;)
        scriptEntry.addObject("duration", Duration.ZERO);
        // Now let's add a delayed task to set it back after the duration
        // Delays are in ticks, so let's multiply our duration (which is in seconds) by 20.
        // 20 ticks per second.
        long delay = (long) (duration.getSeconds() * 20);
        // Set delayed task and put id in a map
        dB.log("Setting delayed task 'RESET ZAP' for '" + script.identify() + "'");
        durations.put(((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().getSaveName() + "," + script.getName(), DenizenAPI.getCurrentInstance().getServer().getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(), new Runnable() {

            @Override
            public void run() {
                dB.log("Running delayed task 'RESET ZAP' for '" + script.identify() + "'");
                try {
                    durations.remove(((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().getSaveName() + "," + script.getName().toUpperCase());
                    execute(scriptEntry);
                } catch (CommandExecutionException e) {
                    dB.echoError(scriptEntry.getResidingQueue(), "Could not run delayed task!");
                    dB.echoError(scriptEntry.getResidingQueue(), e);
                }
            }
        }, delay));
    }
    //
    // FINALLY! ZAP! Change the step in Saves... your step is now ZAPPED!
    // Fun fact: ZAP is named in homage of ZZT-OOPs ZAP command. Google it.
    //
    DenizenAPI.getCurrentInstance().getSaves().set("Players." + ((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().getSaveName() + ".Scripts." + script.getName().toUpperCase() + "." + "Current Step", step);
}
Also used : BukkitScriptEntryData(net.aufdemrand.denizen.BukkitScriptEntryData) net.aufdemrand.denizencore.objects.dScript(net.aufdemrand.denizencore.objects.dScript) Element(net.aufdemrand.denizencore.objects.Element) Duration(net.aufdemrand.denizencore.objects.Duration) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException) InvalidArgumentsException(net.aufdemrand.denizencore.exceptions.InvalidArgumentsException) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException)

Example 9 with CommandExecutionException

use of net.aufdemrand.denizencore.exceptions.CommandExecutionException in project Denizen-For-Bukkit by DenizenScript.

the class NoteCommand method execute.

@Override
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
    String object = (String) scriptEntry.getObject("object");
    Element id = scriptEntry.getElement("id");
    Element remove = scriptEntry.getElement("remove");
    dB.report(scriptEntry, getName(), aH.debugObj("object", object) + id.debug() + remove.debug());
    if (remove.asBoolean()) {
        if (NotableManager.isSaved(id.asString())) {
            NotableManager.remove(id.asString());
            dB.echoDebug(scriptEntry, "notable '" + id.asString() + "' removed");
        } else {
            dB.echoDebug(scriptEntry, id.asString() + " is not saved");
        }
        return;
    }
    String object_type = CoreUtilities.toLowerCase(object.split("@")[0]);
    Class object_class = ObjectFetcher.getObjectClass(object_type);
    if (object_class == null) {
        dB.echoError(scriptEntry.getResidingQueue(), "Invalid object type! Could not fetch '" + object_type + "'!");
        return;
    }
    dObject arg;
    try {
        if (!ObjectFetcher.checkMatch(object_class, object)) {
            dB.echoError(scriptEntry.getResidingQueue(), "'" + object + "' is an invalid " + object_class.getSimpleName() + ".");
            return;
        }
        arg = ObjectFetcher.getObjectFrom(object_class, object);
        if (arg instanceof Notable) {
            ((Notable) arg).makeUnique(id.asString());
        }
    } catch (Exception e) {
        dB.echoError(scriptEntry.getResidingQueue(), "Uh oh! Report this to the Denizen developers! Err: NoteCommandObjectReflection");
        dB.echoError(scriptEntry.getResidingQueue(), e);
    }
}
Also used : Element(net.aufdemrand.denizencore.objects.Element) net.aufdemrand.denizencore.objects.dObject(net.aufdemrand.denizencore.objects.dObject) Notable(net.aufdemrand.denizencore.objects.notable.Notable) InvalidArgumentsException(net.aufdemrand.denizencore.exceptions.InvalidArgumentsException) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException)

Example 10 with CommandExecutionException

use of net.aufdemrand.denizencore.exceptions.CommandExecutionException in project Denizen-For-Bukkit by DenizenScript.

the class SQLCommand method execute.

@Override
public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
    Element action = scriptEntry.getElement("action");
    final Element server = scriptEntry.getElement("server");
    final Element username = scriptEntry.getElement("username");
    final Element password = scriptEntry.getElement("password");
    final Element sqlID = scriptEntry.getElement("sqlid");
    final Element query = scriptEntry.getElement("query");
    dB.report(scriptEntry, getName(), sqlID.debug() + action.debug() + (server != null ? server.debug() : "") + (username != null ? username.debug() : "") + (password != null ? aH.debugObj("password", "NotLogged") : "") + (query != null ? query.debug() : ""));
    if (!action.asString().equalsIgnoreCase("connect") && (!action.asString().equalsIgnoreCase("query") || !scriptEntry.shouldWaitFor())) {
        scriptEntry.setFinished(true);
    }
    try {
        if (action.asString().equalsIgnoreCase("connect")) {
            if (server == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Must specify a server!");
                return;
            }
            if (username == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Must specify a username!");
                return;
            }
            if (password == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Must specify a password!");
                return;
            }
            if (connections.containsKey(sqlID.asString().toUpperCase())) {
                dB.echoError(scriptEntry.getResidingQueue(), "Already connected to a server with ID '" + sqlID.asString() + "'!");
                return;
            }
            Bukkit.getScheduler().runTaskLaterAsynchronously(DenizenAPI.getCurrentInstance(), new Runnable() {

                @Override
                public void run() {
                    Connection con = null;
                    if (dB.verbose) {
                        dB.echoDebug(scriptEntry, "Connecting to " + server.asString());
                    }
                    try {
                        con = getConnection(username.asString(), password.asString(), server.asString());
                    } catch (final Exception e) {
                        Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                            @Override
                            public void run() {
                                dB.echoError(scriptEntry.getResidingQueue(), "SQL Exception: " + e.getMessage());
                                scriptEntry.setFinished(true);
                                if (dB.verbose) {
                                    dB.echoError(scriptEntry.getResidingQueue(), e);
                                }
                            }
                        }, 1);
                    }
                    if (dB.verbose) {
                        dB.echoDebug(scriptEntry, "Connection did not error");
                    }
                    final Connection conn = con;
                    if (con != null) {
                        Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                            @Override
                            public void run() {
                                connections.put(sqlID.asString().toUpperCase(), conn);
                                dB.echoDebug(scriptEntry, "Successfully connected to " + server);
                                scriptEntry.setFinished(true);
                            }
                        }, 1);
                    } else {
                        Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                            @Override
                            public void run() {
                                scriptEntry.setFinished(true);
                                if (dB.verbose) {
                                    dB.echoDebug(scriptEntry, "Connecting errored!");
                                }
                            }
                        }, 1);
                    }
                }
            }, 1);
        } else if (action.asString().equalsIgnoreCase("disconnect")) {
            Connection con = connections.get(sqlID.asString().toUpperCase());
            if (con == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Not connected to server with ID '" + sqlID.asString() + "'!");
                return;
            }
            con.close();
            connections.remove(sqlID.asString().toUpperCase());
            dB.echoDebug(scriptEntry, "Disconnected from '" + sqlID.asString() + "'.");
        } else if (action.asString().equalsIgnoreCase("query")) {
            if (query == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Must specify a query!");
                return;
            }
            final Connection con = connections.get(sqlID.asString().toUpperCase());
            if (con == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Not connected to server with ID '" + sqlID.asString() + "'!");
                return;
            }
            dB.echoDebug(scriptEntry, "Running query " + query.asString());
            if (scriptEntry.shouldWaitFor()) {
                Bukkit.getScheduler().runTaskLaterAsynchronously(DenizenAPI.getCurrentInstance(), new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Statement statement = con.createStatement();
                            ResultSet set = statement.executeQuery(query.asString());
                            ResultSetMetaData rsmd = set.getMetaData();
                            final int columns = rsmd.getColumnCount();
                            Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                                @Override
                                public void run() {
                                    dB.echoDebug(scriptEntry, "Got a query result of " + columns + " columns");
                                }
                            }, 1);
                            int count = 0;
                            dList rows = new dList();
                            while (set.next()) {
                                count++;
                                StringBuilder current = new StringBuilder();
                                for (int i = 0; i < columns; i++) {
                                    current.append(EscapeTags.Escape(set.getString(i + 1))).append("/");
                                }
                                rows.add(current.toString());
                            }
                            scriptEntry.addObject("result", rows);
                            final int finalCount = count;
                            Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                                @Override
                                public void run() {
                                    dB.echoDebug(scriptEntry, "Got a query result of " + finalCount + " rows");
                                    scriptEntry.setFinished(true);
                                }
                            }, 1);
                        } catch (final Exception e) {
                            Bukkit.getScheduler().runTaskLater(DenizenAPI.getCurrentInstance(), new Runnable() {

                                @Override
                                public void run() {
                                    dB.echoError(scriptEntry.getResidingQueue(), "SQL Exception: " + e.getMessage());
                                    scriptEntry.setFinished(true);
                                    if (dB.verbose) {
                                        dB.echoError(scriptEntry.getResidingQueue(), e);
                                    }
                                }
                            }, 1);
                        }
                    }
                }, 1);
            } else {
                Statement statement = con.createStatement();
                ResultSet set = statement.executeQuery(query.asString());
                ResultSetMetaData rsmd = set.getMetaData();
                final int columns = rsmd.getColumnCount();
                dB.echoDebug(scriptEntry, "Got a query result of " + columns + " columns");
                int count = 0;
                dList rows = new dList();
                while (set.next()) {
                    count++;
                    StringBuilder current = new StringBuilder();
                    for (int i = 0; i < columns; i++) {
                        current.append(EscapeTags.Escape(set.getString(i + 1))).append("/");
                    }
                    rows.add(current.toString());
                }
                scriptEntry.addObject("result", rows);
                final int finalCount = count;
                dB.echoDebug(scriptEntry, "Got a query result of " + finalCount + " rows");
            }
        } else if (action.asString().equalsIgnoreCase("update")) {
            if (query == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Must specify an update query!");
                return;
            }
            Connection con = connections.get(sqlID.asString().toUpperCase());
            if (con == null) {
                dB.echoError(scriptEntry.getResidingQueue(), "Not connected to server with ID '" + sqlID.asString() + "'!");
                return;
            }
            dB.echoDebug(scriptEntry, "Running update " + query.asString());
            Statement statement = con.createStatement();
            int affected = statement.executeUpdate(query.asString(), Statement.RETURN_GENERATED_KEYS);
            scriptEntry.addObject("affected_rows", new Element(affected));
            ResultSet set = statement.getGeneratedKeys();
            ResultSetMetaData rsmd = set.getMetaData();
            int columns = rsmd.getColumnCount();
            dB.echoDebug(scriptEntry, "Got a query result of " + columns + " columns");
            dList rows = new dList();
            while (set.next()) {
                StringBuilder current = new StringBuilder();
                for (int i = 0; i < columns; i++) {
                    current.append(EscapeTags.Escape(set.getString(i + 1))).append("/");
                }
                rows.add(current.toString());
            }
            scriptEntry.addObject("result", rows);
            dB.echoDebug(scriptEntry, "Updated " + affected + " rows");
        } else {
            dB.echoError(scriptEntry.getResidingQueue(), "Unknown action '" + action.asString() + "'");
        }
    } catch (SQLException e) {
        dB.echoError(scriptEntry.getResidingQueue(), "SQL Exception: " + e.getMessage());
        if (dB.verbose) {
            dB.echoError(scriptEntry.getResidingQueue(), e);
        }
    }
}
Also used : Element(net.aufdemrand.denizencore.objects.Element) net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList) InvalidArgumentsException(net.aufdemrand.denizencore.exceptions.InvalidArgumentsException) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException)

Aggregations

CommandExecutionException (net.aufdemrand.denizencore.exceptions.CommandExecutionException)21 InvalidArgumentsException (net.aufdemrand.denizencore.exceptions.InvalidArgumentsException)17 Element (net.aufdemrand.denizencore.objects.Element)16 net.aufdemrand.denizen.objects.dLocation (net.aufdemrand.denizen.objects.dLocation)8 net.aufdemrand.denizencore.objects.dList (net.aufdemrand.denizencore.objects.dList)8 Duration (net.aufdemrand.denizencore.objects.Duration)6 BukkitScriptEntryData (net.aufdemrand.denizen.BukkitScriptEntryData)5 net.aufdemrand.denizencore.objects.dScript (net.aufdemrand.denizencore.objects.dScript)5 List (java.util.List)4 net.aufdemrand.denizen.objects.dEntity (net.aufdemrand.denizen.objects.dEntity)4 ScriptEntry (net.aufdemrand.denizencore.scripts.ScriptEntry)4 Player (org.bukkit.entity.Player)4 File (java.io.File)3 net.aufdemrand.denizen.objects.dNPC (net.aufdemrand.denizen.objects.dNPC)3 net.aufdemrand.denizen.objects.dPlayer (net.aufdemrand.denizen.objects.dPlayer)3 net.aufdemrand.denizencore.objects.dObject (net.aufdemrand.denizencore.objects.dObject)3 ScriptQueue (net.aufdemrand.denizencore.scripts.queues.ScriptQueue)3 Location (org.bukkit.Location)2 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)2 Vector (org.bukkit.util.Vector)2