Search in sources :

Example 1 with Handler

use of me.botsko.prism.actions.Handler in project Prism-Bukkit by prism.

the class RecordingTask method insertExtraData.

/**
     *
     * @param keys
     * @throws SQLException
     */
protected void insertExtraData(ArrayList<Handler> extraDataQueue, ResultSet keys) throws SQLException {
    String prefix = plugin.getConfig().getString("prism.mysql.prefix");
    if (extraDataQueue.isEmpty())
        return;
    PreparedStatement s = null;
    final Connection conn = Prism.dbc();
    if (conn == null || conn.isClosed()) {
        Prism.log("Prism database error. Skipping extra data queue insertion.");
        return;
    }
    try {
        conn.setAutoCommit(false);
        s = conn.prepareStatement("INSERT INTO " + prefix + "data_extra (data_id,data) VALUES (?,?)");
        int i = 0;
        while (keys.next()) {
            if (conn.isClosed()) {
                Prism.log("Prism database error. We have to bail in the middle of building bulk insert extra data query.");
                break;
            }
            // @todo should not happen
            if (i >= extraDataQueue.size()) {
                Prism.log("Skipping extra data for " + prefix + "data.id " + keys.getInt(1) + " because the queue doesn't have data for it.");
                continue;
            }
            final Handler a = extraDataQueue.get(i);
            if (a.getData() != null && !a.getData().isEmpty()) {
                s.setInt(1, keys.getInt(1));
                s.setString(2, a.getData());
                s.addBatch();
            }
            i++;
        }
        s.executeBatch();
        if (conn.isClosed()) {
            Prism.log("Prism database error. We have to bail in the middle of building extra data bulk insert query.");
        } else {
            conn.commit();
        }
    } catch (final SQLException e) {
        e.printStackTrace();
        plugin.handleDatabaseException(e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (final SQLException ignored) {
            }
        try {
            conn.close();
        } catch (final SQLException ignored) {
        }
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) Handler(me.botsko.prism.actions.Handler) PreparedStatement(java.sql.PreparedStatement)

Example 2 with Handler

use of me.botsko.prism.actions.Handler in project Prism-Bukkit by prism.

the class RecordingTask method insertActionsIntoDatabase.

/**
     *
     * @throws SQLException
     */
public void insertActionsIntoDatabase() {
    String prefix = plugin.getConfig().getString("prism.mysql.prefix");
    PreparedStatement s = null;
    Connection conn = null;
    int actionsRecorded = 0;
    try {
        int perBatch = plugin.getConfig().getInt("prism.database.actions-per-insert-batch");
        if (perBatch < 1)
            perBatch = 1000;
        if (!RecordingQueue.getQueue().isEmpty()) {
            Prism.debug("Beginning batch insert from queue. " + System.currentTimeMillis());
            final ArrayList<Handler> extraDataQueue = new ArrayList<Handler>();
            conn = Prism.dbc();
            // Handle dead connections
            if (conn == null || conn.isClosed()) {
                if (RecordingManager.failedDbConnectionCount == 0) {
                    Prism.log("Prism database error. Connection should be there but it's not. Leaving actions to log in queue.");
                }
                RecordingManager.failedDbConnectionCount++;
                if (RecordingManager.failedDbConnectionCount > plugin.getConfig().getInt("prism.database.max-failures-before-wait")) {
                    Prism.log("Too many problems connecting. Giving up for a bit.");
                    scheduleNextRecording();
                }
                Prism.debug("Database connection still missing, incrementing count.");
                return;
            } else {
                RecordingManager.failedDbConnectionCount = 0;
            }
            // Connection valid, proceed
            conn.setAutoCommit(false);
            s = conn.prepareStatement("INSERT INTO " + prefix + "data (epoch,action_id,player_id,world_id,block_id,block_subid,old_block_id,old_block_subid,x,y,z) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            int i = 0;
            while (!RecordingQueue.getQueue().isEmpty()) {
                if (conn.isClosed()) {
                    Prism.log("Prism database error. We have to bail in the middle of building primary bulk insert query.");
                    break;
                }
                final Handler a = RecordingQueue.getQueue().poll();
                // poll() returns null if queue is empty
                if (a == null)
                    break;
                int world_id = 0;
                if (Prism.prismWorlds.containsKey(a.getWorldName())) {
                    world_id = Prism.prismWorlds.get(a.getWorldName());
                }
                int action_id = 0;
                if (Prism.prismActions.containsKey(a.getType().getName())) {
                    action_id = Prism.prismActions.get(a.getType().getName());
                }
                int player_id = 0;
                PrismPlayer prismPlayer = PlayerIdentification.cachePrismPlayer(a.getPlayerName());
                if (prismPlayer != null) {
                    player_id = prismPlayer.getId();
                }
                if (world_id == 0 || action_id == 0 || player_id == 0) {
                    // @todo do something, error here
                    Prism.log("Cache data was empty. Please report to developer: world_id:" + world_id + "/" + a.getWorldName() + " action_id:" + action_id + "/" + a.getType().getName() + " player_id:" + player_id + "/" + a.getPlayerName());
                    Prism.log("HOWEVER, this likely means you have a broken prism database installation.");
                    continue;
                }
                if (a.isCanceled())
                    continue;
                actionsRecorded++;
                s.setLong(1, System.currentTimeMillis() / 1000L);
                s.setInt(2, action_id);
                s.setInt(3, player_id);
                s.setInt(4, world_id);
                s.setInt(5, a.getBlockId());
                s.setInt(6, a.getBlockSubId());
                s.setInt(7, a.getOldBlockId());
                s.setInt(8, a.getOldBlockSubId());
                s.setInt(9, (int) a.getX());
                s.setInt(10, (int) a.getY());
                s.setInt(11, (int) a.getZ());
                s.addBatch();
                extraDataQueue.add(a);
                // Break out of the loop and just commit what we have
                if (i >= perBatch) {
                    Prism.debug("Recorder: Batch max exceeded, running insert. Queue remaining: " + RecordingQueue.getQueue().size());
                    break;
                }
                i++;
            }
            s.executeBatch();
            if (conn.isClosed()) {
                Prism.log("Prism database error. We have to bail in the middle of building primary bulk insert query.");
            } else {
                conn.commit();
                Prism.debug("Batch insert was commit: " + System.currentTimeMillis());
            }
            // Save the current count to the queue for short historical data
            plugin.queueStats.addRunCount(actionsRecorded);
            // Insert extra data
            insertExtraData(extraDataQueue, s.getGeneratedKeys());
        }
    } catch (final SQLException e) {
        e.printStackTrace();
        plugin.handleDatabaseException(e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (final SQLException ignored) {
            }
        if (conn != null)
            try {
                conn.close();
            } catch (final SQLException ignored) {
            }
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) Handler(me.botsko.prism.actions.Handler) PreparedStatement(java.sql.PreparedStatement) PrismPlayer(me.botsko.prism.players.PrismPlayer)

Example 3 with Handler

use of me.botsko.prism.actions.Handler in project Prism-Bukkit by prism.

the class LookupCommand method handle.

/**
     * Handle the command
     */
@Override
public void handle(final CallInfo call) {
    // Process and validate all of the arguments
    final QueryParameters parameters = PreprocessArgs.process(plugin, call.getSender(), call.getArgs(), PrismProcessType.LOOKUP, 1, !plugin.getConfig().getBoolean("prism.queries.never-use-defaults"));
    if (parameters == null) {
        return;
    }
    /**
         * Run the lookup itself in an async task so the lookup query isn't done
         * on the main thread
         */
    plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {

        @Override
        public void run() {
            // determine if defaults were used
            final ArrayList<String> defaultsUsed = parameters.getDefaultsUsed();
            String defaultsReminder = "";
            if (!defaultsUsed.isEmpty()) {
                defaultsReminder += "Using defaults:";
                for (final String d : defaultsUsed) {
                    defaultsReminder += " " + d;
                }
            }
            final ActionsQuery aq = new ActionsQuery(plugin);
            final QueryResult results = aq.lookup(parameters, call.getSender());
            String sharingWithPlayers = "";
            for (final CommandSender shareWith : parameters.getSharedPlayers()) {
                sharingWithPlayers += shareWith.getName() + ", ";
            }
            sharingWithPlayers = sharingWithPlayers.substring(0, sharingWithPlayers.isEmpty() ? 0 : sharingWithPlayers.length() - 2);
            // Add current sender
            parameters.addSharedPlayer(call.getSender());
            for (final CommandSender player : parameters.getSharedPlayers()) {
                final boolean isSender = player.getName().equals(call.getSender().getName());
                if (!isSender) {
                    player.sendMessage(Prism.messenger.playerHeaderMsg(ChatColor.YELLOW + "" + ChatColor.ITALIC + call.getSender().getName() + ChatColor.GOLD + " shared these Prism lookup logs with you:"));
                } else if (!sharingWithPlayers.isEmpty()) {
                    player.sendMessage(Prism.messenger.playerHeaderMsg(ChatColor.GOLD + "Sharing results with players: " + ChatColor.YELLOW + "" + ChatColor.ITALIC + sharingWithPlayers));
                }
                if (!results.getActionResults().isEmpty()) {
                    player.sendMessage(Prism.messenger.playerHeaderMsg("Showing " + results.getTotalResults() + " results. Page 1 of " + results.getTotal_pages()));
                    if (!defaultsReminder.isEmpty() && isSender) {
                        player.sendMessage(Prism.messenger.playerSubduedHeaderMsg(defaultsReminder));
                    }
                    final List<Handler> paginated = results.getPaginatedActionResults();
                    if (paginated != null) {
                        int result_count = results.getIndexOfFirstResult();
                        for (final Handler a : paginated) {
                            final ActionMessage am = new ActionMessage(a);
                            if (parameters.allowsNoRadius() || parameters.hasFlag(Flag.EXTENDED) || plugin.getConfig().getBoolean("prism.messenger.always-show-extended")) {
                                am.showExtended();
                            }
                            am.setResultIndex(result_count);
                            player.sendMessage(Prism.messenger.playerMsg(am.getMessage()));
                            result_count++;
                        }
                    } else {
                        player.sendMessage(Prism.messenger.playerError("Pagination can't find anything. Do you have the right page number?"));
                    }
                    if (parameters.hasFlag(Flag.PASTE)) {
                        String paste = "";
                        for (final Handler a : results.getActionResults()) {
                            paste += new ActionMessage(a).getRawMessage() + "\r\n";
                        }
                        player.sendMessage(MiscUtils.paste_results(plugin, paste));
                    }
                } else {
                    if (!defaultsReminder.isEmpty()) {
                        if (isSender) {
                            player.sendMessage(Prism.messenger.playerSubduedHeaderMsg(defaultsReminder));
                        }
                    }
                    if (isSender) {
                        player.sendMessage(Prism.messenger.playerError("Nothing found." + ChatColor.GRAY + " Either you're missing something, or we are."));
                    }
                }
            }
            // Flush timed data
            plugin.eventTimer.printTimeRecord();
        }
    });
}
Also used : QueryResult(me.botsko.prism.actionlibs.QueryResult) ActionsQuery(me.botsko.prism.actionlibs.ActionsQuery) ArrayList(java.util.ArrayList) ActionMessage(me.botsko.prism.actionlibs.ActionMessage) Handler(me.botsko.prism.actions.Handler) SubHandler(me.botsko.prism.commandlibs.SubHandler) CommandSender(org.bukkit.command.CommandSender) ArrayList(java.util.ArrayList) List(java.util.List) QueryParameters(me.botsko.prism.actionlibs.QueryParameters)

Example 4 with Handler

use of me.botsko.prism.actions.Handler in project Prism-Bukkit by prism.

the class ActionsQuery method lookup.

/**
     * 
     * @return
     */
public QueryResult lookup(QueryParameters parameters, CommandSender sender) {
    Player player = null;
    if (sender instanceof Player) {
        player = (Player) sender;
    }
    // If lookup, determine if we need to group
    shouldGroup = false;
    if (parameters.getProcessType().equals(PrismProcessType.LOOKUP)) {
        shouldGroup = true;
        // What to default to
        if (!plugin.getConfig().getBoolean("prism.queries.lookup-auto-group")) {
            shouldGroup = false;
        }
        // Any overriding flags passed?
        if (parameters.hasFlag(Flag.NO_GROUP) || parameters.hasFlag(Flag.EXTENDED)) {
            shouldGroup = false;
        }
    }
    // Pull results
    final List<Handler> actions = new ArrayList<Handler>();
    // Build conditions based off final args
    final String query = qb.getQuery(parameters, shouldGroup);
    if (query != null) {
        Connection conn = null;
        PreparedStatement s = null;
        ResultSet rs = null;
        try {
            plugin.eventTimer.recordTimedEvent("query started");
            conn = Prism.dbc();
            // Handle dead connections
            if (conn == null || conn.isClosed()) {
                if (RecordingManager.failedDbConnectionCount == 0) {
                    Prism.log("Prism database error. Connection should be there but it's not. Leaving actions to log in queue.");
                }
                RecordingManager.failedDbConnectionCount++;
                sender.sendMessage(Prism.messenger.playerError("Database connection was closed, please wait and try again."));
                return new QueryResult(actions, parameters);
            } else {
                RecordingManager.failedDbConnectionCount = 0;
            }
            s = conn.prepareStatement(query);
            rs = s.executeQuery();
            plugin.eventTimer.recordTimedEvent("query returned, building results");
            while (rs.next()) {
                if (rs.getString(3) == null)
                    continue;
                // Convert action ID to name
                // Performance-wise this is a lot faster than table joins
                // and the cache data should always be available
                String actionName = "";
                for (final Entry<String, Integer> entry : Prism.prismActions.entrySet()) {
                    if (entry.getValue() == rs.getInt(3)) {
                        actionName = entry.getKey();
                    }
                }
                if (actionName.isEmpty()) {
                    Prism.log("Record contains action ID that doesn't exist in cache: " + rs.getInt(3));
                    continue;
                }
                // Get the action handler
                final ActionType actionType = Prism.getActionRegistry().getAction(actionName);
                if (actionType == null)
                    continue;
                try {
                    final Handler baseHandler = Prism.getHandlerRegistry().getHandler(actionType.getHandler());
                    // Convert world ID to name
                    // Performance-wise this is typically a lot faster than
                    // table joins
                    String worldName = "";
                    for (final Entry<String, Integer> entry : Prism.prismWorlds.entrySet()) {
                        if (entry.getValue() == rs.getInt(5)) {
                            worldName = entry.getKey();
                        }
                    }
                    // Set all shared values
                    baseHandler.setPlugin(plugin);
                    baseHandler.setType(actionType);
                    baseHandler.setId(rs.getInt(1));
                    baseHandler.setUnixEpoch(rs.getString(2));
                    baseHandler.setPlayerName(rs.getString(4));
                    baseHandler.setWorldName(worldName);
                    baseHandler.setX(rs.getInt(6));
                    baseHandler.setY(rs.getInt(7));
                    baseHandler.setZ(rs.getInt(8));
                    baseHandler.setBlockId(rs.getInt(9));
                    baseHandler.setBlockSubId(rs.getInt(10));
                    baseHandler.setOldBlockId(rs.getInt(11));
                    baseHandler.setOldBlockSubId(rs.getInt(12));
                    baseHandler.setData(rs.getString(13));
                    baseHandler.setMaterialAliases(Prism.getItems());
                    // Set aggregate counts if a lookup
                    int aggregated = 0;
                    if (shouldGroup) {
                        aggregated = rs.getInt(14);
                    }
                    baseHandler.setAggregateCount(aggregated);
                    actions.add(baseHandler);
                } catch (final Exception e) {
                    if (!rs.isClosed()) {
                        Prism.log("Ignoring data from record #" + rs.getInt(1) + " because it caused an error:");
                    }
                    e.printStackTrace();
                }
            }
        } catch (final SQLException e) {
            plugin.handleDatabaseException(e);
        } finally {
            if (rs != null)
                try {
                    rs.close();
                } catch (final SQLException ignored) {
                }
            if (s != null)
                try {
                    s.close();
                } catch (final SQLException ignored) {
                }
            if (conn != null)
                try {
                    conn.close();
                } catch (final SQLException ignored) {
                }
        }
    }
    // Build result object
    final QueryResult res = new QueryResult(actions, parameters);
    res.setPerPage(parameters.getPerPage());
    // need a cache.
    if (parameters.getProcessType().equals(PrismProcessType.LOOKUP)) {
        String keyName = "console";
        if (player != null) {
            keyName = player.getName();
        }
        if (plugin.cachedQueries.containsKey(keyName)) {
            plugin.cachedQueries.remove(keyName);
        }
        plugin.cachedQueries.put(keyName, res);
        // We also need to share these results with the -share-with players.
        for (final CommandSender sharedPlayer : parameters.getSharedPlayers()) {
            plugin.cachedQueries.put(sharedPlayer.getName(), res);
        }
    }
    plugin.eventTimer.recordTimedEvent("results object completed");
    // Return it
    return res;
}
Also used : Player(org.bukkit.entity.Player) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) Handler(me.botsko.prism.actions.Handler) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) CommandSender(org.bukkit.command.CommandSender)

Example 5 with Handler

use of me.botsko.prism.actions.Handler in project Prism-Bukkit by prism.

the class PrismPlayerEvents method onPlayerBucketFill.

/**
     * 
     * @param event
     */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketFill(final PlayerBucketFillEvent event) {
    final Player player = event.getPlayer();
    if (!Prism.getIgnore().event("bucket-fill", player))
        return;
    final Block spot = event.getBlockClicked().getRelative(event.getBlockFace());
    String liquid_type = "milk";
    if (spot.getTypeId() == 8 || spot.getTypeId() == 9) {
        liquid_type = "water";
    } else if (spot.getTypeId() == 10 || spot.getTypeId() == 11) {
        liquid_type = "lava";
    }
    final Handler pa = ActionFactory.createPlayer("bucket-fill", player, liquid_type);
    // Override the location with the area taken
    pa.setX(spot.getX());
    pa.setY(spot.getY());
    pa.setZ(spot.getZ());
    RecordingQueue.addToQueue(pa);
}
Also used : Player(org.bukkit.entity.Player) Block(org.bukkit.block.Block) Handler(me.botsko.prism.actions.Handler) EventHandler(org.bukkit.event.EventHandler) EventHandler(org.bukkit.event.EventHandler)

Aggregations

Handler (me.botsko.prism.actions.Handler)12 QueryResult (me.botsko.prism.actionlibs.QueryResult)5 SubHandler (me.botsko.prism.commandlibs.SubHandler)5 ActionMessage (me.botsko.prism.actionlibs.ActionMessage)4 ActionsQuery (me.botsko.prism.actionlibs.ActionsQuery)4 QueryParameters (me.botsko.prism.actionlibs.QueryParameters)4 Player (org.bukkit.entity.Player)4 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 SQLException (java.sql.SQLException)3 ArrayList (java.util.ArrayList)3 EventHandler (org.bukkit.event.EventHandler)3 List (java.util.List)2 BlockStateChange (me.botsko.prism.events.BlockStateChange)2 BlockState (org.bukkit.block.BlockState)2 CommandSender (org.bukkit.command.CommandSender)2 ResultSet (java.sql.ResultSet)1 PrismProcessAction (me.botsko.prism.actions.PrismProcessAction)1 PrismApplierCallback (me.botsko.prism.appliers.PrismApplierCallback)1 Undo (me.botsko.prism.appliers.Undo)1