Search in sources :

Example 1 with ActionTypeImpl

use of me.botsko.prism.actionlibs.ActionTypeImpl in project Prism-Bukkit by prism.

the class ActionParameter method process.

@Override
public void process(QueryParameters query, String alias, String input, CommandSender sender) {
    // Check match type
    MatchRule match = MatchRule.INCLUDE;
    if (input.startsWith("!")) {
        match = MatchRule.EXCLUDE;
    }
    final String[] actions = input.split(",");
    if (actions.length > 0) {
        for (final String action : actions) {
            // Find all actions that match the action provided - whether the
            // full name or
            // short name.
            final ArrayList<ActionTypeImpl> actionTypes = Prism.getActionRegistry().getActionsByShortName(action.replace("!", ""));
            if (!actionTypes.isEmpty()) {
                List<String> noPermission = new ArrayList<>();
                for (final ActionTypeImpl actionType : actionTypes) {
                    // Ensure the action allows this process type
                    if ((query.getProcessType().equals(PrismProcessType.ROLLBACK) && !actionType.canRollback()) || (query.getProcessType().equals(PrismProcessType.RESTORE) && !actionType.canRestore())) {
                        // );
                        continue;
                    }
                    if (sender != null && !sender.hasPermission(getPermission() + "." + actionType.getName())) {
                        noPermission.add(actionType.getName());
                        continue;
                    }
                    query.addActionType(actionType.getName(), match);
                }
                if (!noPermission.isEmpty()) {
                    String message = "Ignoring action '" + action + "' because you don't have permission for ";
                    if (noPermission.size() != 1) {
                        message += "any of " + Joiner.on(',').join(noPermission) + ".";
                    } else if (noPermission.get(0).equals(action)) {
                        message += "it.";
                    } else {
                        message += noPermission.get(0) + ".";
                    }
                    Prism.messenger.sendMessage(sender, Prism.messenger.playerError(message));
                }
            } else {
                if (sender != null) {
                    Prism.messenger.sendMessage(sender, Prism.messenger.playerError("Ignoring action '" + action.replace("!", "") + "' because it's unrecognized. Did you mean '" + LevenshteinDistance.getClosestAction(action) + "'? Type '/prism params' for help."));
                }
            }
        }
        // If none were valid, we end here.
        if (query.getActionTypes().size() == 0) {
            throw new IllegalArgumentException("Action parameter value not recognized. Try /pr ? for help");
        }
    }
}
Also used : ArrayList(java.util.ArrayList) MatchRule(me.botsko.prism.api.actions.MatchRule) ActionTypeImpl(me.botsko.prism.actionlibs.ActionTypeImpl)

Example 2 with ActionTypeImpl

use of me.botsko.prism.actionlibs.ActionTypeImpl in project Prism-Bukkit by prism.

the class SqlSelectQueryBuilder method executeSelect.

@Override
public QueryResult executeSelect(TimeTaken eventTimer) {
    final List<Handler> actions = new ArrayList<>();
    // Build conditions based off final args
    final String query = getQuery(parameters, shouldGroup);
    eventTimer.recordTimedEvent("query started");
    try (Connection conn = Prism.getPrismDataSource().getDataSource().getConnection();
        PreparedStatement s = conn.prepareStatement(query);
        ResultSet rs = s.executeQuery()) {
        RecordingManager.failedDbConnectionCount = 0;
        eventTimer.recordTimedEvent("query returned, building results");
        Map<Integer, String> worldsInverse = new HashMap<>();
        for (final Entry<String, Integer> entry : Prism.prismWorlds.entrySet()) {
            worldsInverse.put(entry.getValue(), entry.getKey());
        }
        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
            int actionId = rs.getInt(3);
            String actionName = "";
            for (final Entry<String, Integer> entry : Prism.prismActions.entrySet()) {
                if (entry.getValue() == actionId) {
                    actionName = entry.getKey();
                }
            }
            if (actionName.isEmpty()) {
                Prism.warn("Record contains action ID that doesn't exist in cache: " + actionId + ", cacheSize=" + Prism.prismActions.size());
                continue;
            }
            // Get the action handler
            final ActionTypeImpl actionType = Prism.getActionRegistry().getAction(actionName);
            if (actionType == null) {
                continue;
            }
            long rowId = 0;
            try {
                final Handler baseHandler = Prism.getHandlerRegistry().create(actionType.getHandler());
                // Convert world ID to name
                // Performance-wise this is typically a lot faster than
                // table joins
                rowId = rs.getLong(1);
                // Set all shared values
                baseHandler.setActionType(actionType);
                baseHandler.setId(rowId);
                baseHandler.setUnixEpoch(rs.getLong(2));
                String worldName = worldsInverse.getOrDefault(rs.getInt(5), "");
                baseHandler.setWorld(Bukkit.getWorld(worldName));
                baseHandler.setX(rs.getInt(6));
                baseHandler.setY(rs.getInt(7));
                baseHandler.setZ(rs.getInt(8));
                int blockId = rs.getInt(9);
                int blockSubId = rs.getInt(10);
                int oldBlockId = rs.getInt(11);
                int oldBlockSubId = rs.getInt(12);
                String extraData = rs.getString(13);
                boolean validBlockId = false;
                boolean validOldBlockId = false;
                MaterialState current = Prism.getItems().idsToMaterial(blockId, blockSubId, false);
                if (current != null) {
                    ItemStack item = current.asItem();
                    BlockData block = current.asBlockData();
                    if (block != null) {
                        validBlockId = true;
                        baseHandler.setMaterial(block.getMaterial());
                        baseHandler.setBlockData(block);
                        baseHandler.setDurability((short) 0);
                    } else if (item != null) {
                        validBlockId = true;
                        baseHandler.setMaterial(item.getType());
                        BlockData newData;
                        try {
                            newData = Bukkit.createBlockData(item.getType());
                        } catch (IllegalArgumentException e) {
                            // This exception occurs, for example, with "ItemStack{DIAMOND_LEGGINGS x 1}"
                            Prism.debug("IllegalArgumentException for record #" + rowId + " calling createBlockData for " + item.toString());
                            newData = null;
                        }
                        baseHandler.setBlockData(newData);
                        baseHandler.setDurability((short) ItemUtils.getItemDamage(item));
                    }
                }
                MaterialState old = Prism.getItems().idsToMaterial(oldBlockId, oldBlockSubId, false);
                if (old != null) {
                    ItemStack oldItem = old.asItem();
                    BlockData oldBlock = old.asBlockData();
                    validOldBlockId = true;
                    if (oldBlock != null) {
                        baseHandler.setOldMaterial(oldBlock.getMaterial());
                        baseHandler.setOldBlockData(oldBlock);
                        baseHandler.setOldDurability((short) 0);
                    } else {
                        baseHandler.setOldMaterial(oldItem.getType());
                        baseHandler.setOldBlockData(Bukkit.createBlockData(oldItem.getType()));
                        baseHandler.setOldDurability((short) ItemUtils.getItemDamage(oldItem));
                    }
                }
                if (!validBlockId && !validOldBlockId) {
                    // Entry could not be converted to a block or an item
                    boolean logWarning;
                    // The current item is likely a spawn or death event for an entity, for example, a cow or horse
                    logWarning = blockId != 0 || oldBlockId != 0 || extraData == null || !extraData.contains("entity_name");
                    if (logWarning) {
                        String itemMetadataDesc;
                        if (extraData == null) {
                            itemMetadataDesc = "";
                        } else {
                            itemMetadataDesc = ", metadata=" + extraData;
                        }
                        if (blockId > 0) {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "block_id=" + blockId + ", block_subid=" + blockSubId + itemMetadataDesc);
                        } else if (oldBlockId > 0) {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "old_block_id=" + oldBlockId + ", old_block_subid=" + oldBlockSubId + itemMetadataDesc);
                        } else {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "block_id=0, old_block_id=0" + itemMetadataDesc);
                        }
                    }
                }
                // data
                try {
                    baseHandler.deserialize(extraData);
                } catch (JsonSyntaxException e) {
                    if (Prism.isDebug()) {
                        Prism.warn("Deserialization Error: " + e.getLocalizedMessage(), e);
                    }
                }
                // player
                baseHandler.setSourceName(rs.getString(4));
                // player_uuid
                try {
                    // Calls UUID.fromString, must handle potential exceptions
                    OfflinePlayer offline = Bukkit.getOfflinePlayer(SqlPlayerIdentificationHelper.uuidFromDbString(rs.getString(14)));
                    // Fake player
                    if (offline.hasPlayedBefore()) {
                        baseHandler.setUuid(offline.getUniqueId());
                    }
                } catch (IllegalArgumentException | NullPointerException e) {
                // Not a valid uuid
                }
                // Set aggregate counts if a lookup
                int aggregated = 0;
                if (shouldGroup) {
                    aggregated = rs.getInt(15);
                }
                baseHandler.setAggregateCount(aggregated);
                actions.add(baseHandler);
            } catch (final SQLException e) {
                Prism.warn("Ignoring data from record #" + rowId + " because it caused an error:", e);
            }
        }
    } catch (NullPointerException e) {
        if (RecordingManager.failedDbConnectionCount == 0) {
            Prism.log("Prism database error. Connection missing. Leaving actions to log in queue.");
            Prism.debug(e.getMessage());
        }
        RecordingManager.failedDbConnectionCount++;
        return new QueryResult(actions, parameters);
    } catch (SQLException e) {
        Prism.getPrismDataSource().handleDataSourceException(e);
    }
    return new QueryResult(actions, parameters);
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) QueryResult(me.botsko.prism.actionlibs.QueryResult) ResultSet(java.sql.ResultSet) OfflinePlayer(org.bukkit.OfflinePlayer) BlockData(org.bukkit.block.data.BlockData) Connection(java.sql.Connection) Handler(me.botsko.prism.api.actions.Handler) PreparedStatement(java.sql.PreparedStatement) JsonSyntaxException(com.google.gson.JsonSyntaxException) ItemStack(org.bukkit.inventory.ItemStack) ActionTypeImpl(me.botsko.prism.actionlibs.ActionTypeImpl) MaterialState(me.botsko.prism.api.objects.MaterialState)

Aggregations

ArrayList (java.util.ArrayList)2 ActionTypeImpl (me.botsko.prism.actionlibs.ActionTypeImpl)2 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 HashMap (java.util.HashMap)1 QueryResult (me.botsko.prism.actionlibs.QueryResult)1 Handler (me.botsko.prism.api.actions.Handler)1 MatchRule (me.botsko.prism.api.actions.MatchRule)1 MaterialState (me.botsko.prism.api.objects.MaterialState)1 OfflinePlayer (org.bukkit.OfflinePlayer)1 BlockData (org.bukkit.block.data.BlockData)1 ItemStack (org.bukkit.inventory.ItemStack)1