Search in sources :

Example 1 with MaterialState

use of me.botsko.prism.api.objects.MaterialState in project Prism-Bukkit by prism.

the class SqlBlockReportQueryBuilder method report.

@Override
public void report(CommandSender sender) {
    String playerName = null;
    for (String name : parameters.getPlayerNames().keySet()) {
        playerName = name;
    }
    Prism.messenger.sendMessage(sender, Prism.messenger.playerSubduedHeaderMsg(Il8nHelper.formatMessage("actionreport-blockChange", playerName)));
    final int colTextLen = 20;
    final int colIntLen = 12;
    try (Connection conn = dataSource.getDataSource().getConnection();
        PreparedStatement s = conn.prepareStatement(getQuery(parameters, shouldGroup));
        ResultSet rs = s.executeQuery()) {
        Prism.messenger.sendMessage(sender, Prism.messenger.playerHeaderMsg(Il8nHelper.getMessage("report-block-changes").replaceText("<player>", Component.text(playerName).color(NamedTextColor.DARK_AQUA))));
        Prism.messenger.sendMessage(sender, Prism.messenger.playerMsg(Component.text(TypeUtils.padStringRight("Block", colTextLen) + TypeUtils.padStringRight("Placed", colIntLen) + TypeUtils.padStringRight("Broken", colIntLen))));
        while (rs.next()) {
            int blockId = rs.getInt(1);
            MaterialState state = Prism.getItems().idsToMaterial(blockId, 0, true);
            final String alias;
            if (state == null) {
                alias = "UnknownMaterial_BlockId_" + blockId;
            } else {
                BlockData block = state.asBlockData();
                ItemStack item = state.asItem();
                if (block != null) {
                    alias = Prism.getItems().getAlias(block.getMaterial(), block);
                } else if (item != null) {
                    alias = Prism.getItems().getAlias(item);
                } else {
                    alias = "InvalidState_" + state + "_BlockId_" + blockId;
                }
            }
            final int placed = rs.getInt(2);
            final int broken = rs.getInt(3);
            final String colAlias = TypeUtils.padStringRight(alias, colTextLen);
            final String colPlaced = TypeUtils.padStringRight("" + placed, colIntLen);
            final String colBroken = TypeUtils.padStringRight("" + broken, colIntLen);
            Prism.messenger.sendMessage(sender, Prism.messenger.playerMsg(Component.text(colAlias).color(NamedTextColor.DARK_AQUA).append(Component.text(colPlaced).color(NamedTextColor.GREEN)).append(Component.text(colBroken).color(NamedTextColor.RED))));
        }
    } catch (SQLException e) {
        dataSource.handleDataSourceException(e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) BlockData(org.bukkit.block.data.BlockData) ItemStack(org.bukkit.inventory.ItemStack) MaterialState(me.botsko.prism.api.objects.MaterialState)

Example 2 with MaterialState

use of me.botsko.prism.api.objects.MaterialState in project Prism-Bukkit by prism.

the class SqlSelectQueryBuilder method blockCondition.

private void blockCondition() {
    // Blocks
    final Set<Material> blockFilters = parameters.getBlockFilters();
    if (!blockFilters.isEmpty()) {
        final String[] blockArr = new String[blockFilters.size()];
        int i = 0;
        for (Material m : blockFilters) {
            Set<IntPair> allIds = Prism.getItems().materialToAllIds(m);
            StringBuilder blockIds = new StringBuilder("(");
            for (IntPair pair : allIds) {
                blockIds.append(pair.first).append(',');
            }
            String in = blockIds.append(')').toString().replace(",)", ")");
            blockArr[i++] = tableNameData + ".block_id IN " + in;
        }
        addCondition(buildGroupConditions(null, blockArr, "%s%s", "OR", null));
    }
    Set<MaterialState> blockDataFilters = parameters.getBlockDataFilters();
    if (!blockDataFilters.isEmpty()) {
        final ArrayList<String> blockArr = new ArrayList<>();
        for (MaterialState data : blockDataFilters) {
            Set<IntPair> pairs = Prism.getItems().partialBlockDataIds(data.material, data.state);
            for (IntPair pair : pairs) {
                blockArr.add(tableNameData + ".block_id = " + pair.first + " AND " + tableNameData + ".block_subid = " + pair.second);
            }
        }
        addCondition(buildGroupConditions(null, blockArr.toArray(new String[0]), "%s%s", "OR", null));
    }
}
Also used : ArrayList(java.util.ArrayList) Material(org.bukkit.Material) IntPair(me.botsko.prism.utils.IntPair) MaterialState(me.botsko.prism.api.objects.MaterialState)

Example 3 with MaterialState

use of me.botsko.prism.api.objects.MaterialState in project Prism-Bukkit by prism.

the class MaterialAliases method idsToMaterial.

/**
 * .
 *
 * @param blockId           int
 * @param blockSubId        logMaterialErrorsint
 * @param logMaterialErrors boolean.
 * @return MaterialState
 */
public MaterialState idsToMaterial(int blockId, int blockSubId, Boolean logMaterialErrors) {
    MaterialState cachedMaterial = fromCache(blockId, blockSubId);
    if (cachedMaterial != null) {
        return cachedMaterial;
    }
    MaterialState result = new MaterialState();
    SqlIdMapQuery query = new SqlIdMapQuery(Prism.getPrismDataSource());
    query.findMaterial(blockId, blockSubId, (material, state) -> {
        result.material = Material.matchMaterial(material.toUpperCase(Locale.ENGLISH));
        result.state = state;
        if (result.material != null) {
            storeCache(result.material, result.state, blockId, blockSubId);
        }
    }, () -> {
        if (logMaterialErrors) {
            Prism.log("matError: [" + blockId + ", " + blockSubId + "] -> ???");
        }
    });
    if (result.material == null) {
        return null;
    }
    return result;
}
Also used : SqlIdMapQuery(me.botsko.prism.database.sql.SqlIdMapQuery) MaterialState(me.botsko.prism.api.objects.MaterialState)

Example 4 with MaterialState

use of me.botsko.prism.api.objects.MaterialState 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

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