Search in sources :

Example 36 with Query

use of me.staartvin.statz.database.datatype.Query in project Statz by Staartvin.

the class MySQLConnector method setBatchObjects.

@Override
public void setBatchObjects(final Table table, final List<Query> queries, int mode) {
    // Run SQLite query async to not disturb the main Server thread
    Connection conn = getConnection();
    Statement stmt = null;
    try {
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        for (Query query : queries) {
            StringBuilder columnNames = new StringBuilder("(");
            StringBuilder resultNames = new StringBuilder("(");
            for (final Entry<String, String> result : query.getEntrySet()) {
                columnNames.append(result.getKey() + ",");
                try {
                    // Try to check if it is an integer
                    Integer.parseInt(result.getValue());
                    resultNames.append(result.getValue() + ",");
                } catch (final NumberFormatException e) {
                    try {
                        // Try to check if it is an double
                        Double.parseDouble(result.getValue());
                        resultNames.append(result.getValue() + ",");
                    } catch (NumberFormatException ev) {
                        resultNames.append("'" + result.getValue().replace("'", "''") + "',");
                    }
                }
            }
            // Remove last comma
            columnNames = new StringBuilder(columnNames.substring(0, columnNames.lastIndexOf(",")) + ")");
            resultNames = new StringBuilder(resultNames.substring(0, resultNames.lastIndexOf(",")) + ")");
            String update = "INSERT INTO " + table.getTableName() + " " + columnNames.toString() + " VALUES " + resultNames;
            String onDuplicate = "";
            if (query.hasColumn("value")) {
                if (mode == 1) {
                    // Override current value
                    onDuplicate = " ON DUPLICATE KEY UPDATE value=" + query.getValue();
                } else {
                    // Add to current value
                    onDuplicate = " ON DUPLICATE KEY UPDATE value=value+" + query.getValue();
                }
            } else {
                onDuplicate = " ON DUPLICATE KEY UPDATE playerName='" + query.getValue("playerName") + "'";
            }
            update += onDuplicate;
            stmt.addBatch(update);
        }
        stmt.executeBatch();
        if (!conn.getAutoCommit()) {
            conn.commit();
        }
    } catch (BatchUpdateException b) {
        plugin.getLogger().log(Level.SEVERE, "Couldn't execute MySQL statement:", b);
    } catch (SQLException ex) {
        plugin.getLogger().log(Level.SEVERE, "Couldn't execute MySQL statement:", ex);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Also used : Query(me.staartvin.statz.database.datatype.Query)

Example 37 with Query

use of me.staartvin.statz.database.datatype.Query in project Statz by Staartvin.

the class SQLiteConnector method getObjects.

@Override
public List<Query> getObjects(Table table, RowRequirement... requirements) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    final List<Query> results = new ArrayList<>();
    try {
        connection = getConnection();
        // Create SQL query to retrieve data
        if (requirements == null || requirements.length == 0) {
            // No requirements, so we can grab all data in the table.
            ps = connection.prepareStatement("SELECT * FROM " + table.getTableName() + ";");
        } else {
            // We have requirements, so we need to filter the data using WHERE clause of SQL.
            StringBuilder builder = new StringBuilder(String.format("SELECT * FROM %s WHERE ", table.getTableName()));
            // Create a SQL WHERE string.
            for (int i = 0; i < requirements.length; i++) {
                RowRequirement requirement = requirements[i];
                if (i == requirements.length - 1) {
                    builder.append(String.format("%s = '%s';", requirement.getColumnName(), requirement.getColumnValue()));
                } else {
                    builder.append(String.format("%s = '%s' AND ", requirement.getColumnName(), requirement.getColumnValue()));
                }
            }
            ps = connection.prepareStatement(builder.toString());
        }
        rs = ps.executeQuery();
        while (rs.next()) {
            final HashMap<String, String> result = new HashMap<>();
            // Populate hashmap
            for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                final String columnName = rs.getMetaData().getColumnName(i + 1);
                final String value = rs.getObject(i + 1).toString();
                // Put value in hashmap if not null, otherwise just put
                // empty string
                result.put(columnName, (value != null ? value : ""));
            }
            results.add(new Query(result));
        }
    } catch (final SQLException ex) {
        plugin.getLogger().log(Level.SEVERE, "Couldn't execute SQLite statement:", ex);
        return results;
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (final SQLException ex) {
            plugin.getLogger().log(Level.SEVERE, "Failed to close SQLite connection: ", ex);
        }
    }
    return results;
}
Also used : Query(me.staartvin.statz.database.datatype.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RowRequirement(me.staartvin.statz.database.datatype.RowRequirement)

Example 38 with Query

use of me.staartvin.statz.database.datatype.Query in project Statz by Staartvin.

the class CommandsPerformedListener method onPerformCommand.

@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPerformCommand(final PlayerCommandPreprocessEvent event) {
    final PlayerStat stat = PlayerStat.COMMANDS_PERFORMED;
    // Get player
    final Player player = event.getPlayer();
    // Do general check
    if (!plugin.doGeneralCheck(player, stat))
        return;
    String message = event.getMessage();
    int subString = message.indexOf(" ");
    String command = "";
    String arguments = "";
    if (subString > 0) {
        command = message.substring(0, subString).trim();
        arguments = message.substring(subString).trim();
    } else {
        command = message.trim();
    }
    Query query = StatzUtil.makeQuery("uuid", player.getUniqueId(), "value", 1, "world", player.getWorld().getName(), "command", command, "arguments", arguments);
    // Update value to new stat.
    plugin.getDataManager().setPlayerInfo(player.getUniqueId(), stat, query);
}
Also used : Player(org.bukkit.entity.Player) Query(me.staartvin.statz.database.datatype.Query) PlayerStat(me.staartvin.statz.datamanager.player.PlayerStat) EventHandler(org.bukkit.event.EventHandler)

Example 39 with Query

use of me.staartvin.statz.database.datatype.Query in project Statz by Staartvin.

the class DataManager method getFreshPlayerInfo.

/**
 * Get data of a player for a given statistic. This method will obtain 'fresh' data from the database, meaning
 * that it will ignore cached data. Hence, this method will block the thread it is ran on. It is therefore
 * advised to run this method asynchronously.
 * <br>
 * <br>
 * It is recommended to use another method to obtain the data of a player when it is not loaded into the cache
 * yet: using {@link #loadPlayerData(UUID, PlayerStat)}, the retrieved data will also be stored in the cache, so
 * you can retrieve it the next time without making an expensive call to the database.
 *
 * @param uuid     UUID of the player.
 * @param statType Type of statistic.
 * @return fresh player data in the form of a {@link PlayerInfo} object.
 * @throws IllegalArgumentException if the given uuid is null.
 */
public PlayerInfo getFreshPlayerInfo(UUID uuid, PlayerStat statType) throws IllegalArgumentException {
    if (uuid == null) {
        throw new IllegalArgumentException("UUID cannot be null.");
    }
    Table table = DatabaseConnector.getTable(statType);
    List<Query> databaseRows = plugin.getDatabaseConnector().getObjects(table, new RowRequirement("uuid", uuid.toString()));
    PlayerInfo info = new PlayerInfo(uuid);
    info.setData(statType, databaseRows);
    return info;
}
Also used : Table(me.staartvin.statz.database.datatype.Table) Query(me.staartvin.statz.database.datatype.Query) PlayerInfo(me.staartvin.statz.datamanager.player.PlayerInfo) RowRequirement(me.staartvin.statz.database.datatype.RowRequirement)

Example 40 with Query

use of me.staartvin.statz.database.datatype.Query in project Statz by Staartvin.

the class PlayerInfo method toString.

@Override
public String toString() {
    StringBuilder endString = new StringBuilder("PlayerInfo of " + this.getUUID() + ": {");
    StringBuilder queryString;
    for (Map.Entry<PlayerStat, List<Query>> entry : statistics.entrySet()) {
        PlayerStat statType = entry.getKey();
        List<Query> queries = entry.getValue();
        queryString = new StringBuilder(statType + ": {");
        for (Query q : queries) {
            queryString.append(q.toString()).append(", ");
        }
        int lastComma = queryString.lastIndexOf(",");
        if (lastComma >= 0) {
            queryString.deleteCharAt(lastComma);
        }
        queryString.append("}, ");
        endString.append(queryString.toString().trim());
    }
    endString = new StringBuilder(endString.toString().trim());
    endString.append("}");
    return endString.toString();
}
Also used : Query(me.staartvin.statz.database.datatype.Query)

Aggregations

Query (me.staartvin.statz.database.datatype.Query)44 Test (org.junit.Test)25 PlayerInfo (me.staartvin.statz.datamanager.player.PlayerInfo)13 PlayerStat (me.staartvin.statz.datamanager.player.PlayerStat)11 ArrayList (java.util.ArrayList)8 UUID (java.util.UUID)6 RowRequirement (me.staartvin.statz.database.datatype.RowRequirement)4 HashMap (java.util.HashMap)2 Material (org.bukkit.Material)2 Player (org.bukkit.entity.Player)2 Inventory (org.bukkit.inventory.Inventory)2 ItemStack (org.bukkit.inventory.ItemStack)2 ItemMeta (org.bukkit.inventory.meta.ItemMeta)2 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 Date (java.util.Date)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1