CommandUseTable updated the the save method

This commit is contained in:
Rsl1122 2017-08-24 12:53:14 +03:00
parent a920c4254b
commit 11ba16d918
11 changed files with 100 additions and 232 deletions

View File

@ -104,7 +104,7 @@ public class ManageRestoreCommand extends SubCommand {
if (ManageUtils.clearAndCopy(database, backupDB)) {
if (database.getConfigName().equals(plugin.getDB().getConfigName())) {
plugin.getDataCache().getCommandUseFromDb();
// plugin.getDataCache().getCommandUseFromDb();
}
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_COPY_SUCCESS).toString());

View File

@ -213,17 +213,6 @@ public abstract class Database {
*/
public abstract boolean removeAllData();
/**
* Used to save CommandUse map.
*
* @param data String command (key), Integer times used
* @throws SQLException If a database error occurs.
* @throws NullPointerException If the database has not initialized tables.
*/
public void saveCommandUse(Map<String, Integer> data) throws SQLException {
commandUseTable.saveCommandUse(data);
}
/**
* Used to fetch the saved UUIDs in the users table.
*

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Select;
@ -25,6 +24,7 @@ public class CommandUseTable extends Table {
private final String columnCommand = "command";
private final String columnTimesUsed = "times_used";
private final String columnServerID = "server_id";
private final ServerTable serverTable;
/**
@ -71,7 +71,6 @@ public class CommandUseTable extends Table {
* @throws SQLException
*/
public Map<String, Integer> getCommandUse(UUID serverUUID) throws SQLException {
ServerTable serverTable = db.getServerTable();
Benchmark.start("Get CommandUse");
Map<String, Integer> commandUse = new HashMap<>();
PreparedStatement statement = null;
@ -100,70 +99,31 @@ public class CommandUseTable extends Table {
}
}
/**
* @param data
* @throws SQLException
*/
public void saveCommandUse(Map<String, Integer> data) throws SQLException {
if (Verify.isEmpty(data)) {
public void commandUsed(String command) throws SQLException {
if (command.length() > 20) {
return;
}
Benchmark.start("Save Commanduse");
Map<String, Integer> newData = new HashMap<>(data);
Map<String, Integer> saved = getCommandUse();
newData.keySet().removeAll(saved.keySet());
insertCommands(newData);
Map<String, Integer> updateData = new HashMap<>(data);
updateData.keySet().removeAll(newData.keySet());
for (Map.Entry<String, Integer> savedEntry : saved.entrySet()) {
String cmd = savedEntry.getKey();
// IMPORTANT - not using saved as value
Integer toSave = updateData.get(cmd);
if (toSave != null && toSave <= savedEntry.getValue()) {
updateData.remove(cmd);
}
}
updateCommands(updateData);
Benchmark.stop("Database", "Save Commanduse");
db.setAvailable();
}
private void updateCommands(Map<String, Integer> data) throws SQLException {
PreparedStatement statement = null;
try {
String updateStatement = "UPDATE " + tableName + " SET " +
columnTimesUsed + "=? " +
"WHERE (" + columnCommand + "=?) AND (" +
columnServerID + "=" + serverTable.statementSelectServerID + ")";
statement = prepareStatement(updateStatement);
statement = prepareStatement("UPDATE " + tableName + " SET "
+ columnTimesUsed + "=" + columnTimesUsed + "+ 1" +
" WHERE " + columnServerID + "=" + serverTable.statementSelectServerID +
" AND " + columnCommand + "=?");
statement.setString(1, Plan.getServerUUID().toString());
statement.setString(2, command);
int success = statement.executeUpdate();
for (Map.Entry<String, Integer> entrySet : data.entrySet()) {
String key = entrySet.getKey();
Integer amount = entrySet.getValue();
if (key.length() > 20) {
continue;
}
statement.setInt(1, amount);
statement.setString(2, key);
statement.setString(3, Plan.getServerUUID().toString());
statement.addBatch();
}
statement.executeBatch();
commit(statement.getConnection());
if (success == 0) {
insertCommand(command);
}
} finally {
close(statement);
}
}
private void insertCommands(Map<String, Integer> data) throws SQLException {
private void insertCommand(String command) throws SQLException {
PreparedStatement statement = null;
try {
String insertStatement = "INSERT INTO " + tableName + " ("
@ -172,21 +132,11 @@ public class CommandUseTable extends Table {
+ columnServerID
+ ") VALUES (?, ?, " + serverTable.statementSelectServerID + ")";
statement = prepareStatement(insertStatement);
for (Map.Entry<String, Integer> entrySet : data.entrySet()) {
String key = entrySet.getKey();
Integer amount = entrySet.getValue();
statement.setString(1, command);
statement.setInt(2, 1);
statement.setString(3, Plan.getServerUUID().toString());
statement.execute();
if (key.length() > 20) {
continue;
}
statement.setString(1, key);
statement.setInt(2, amount);
statement.setString(3, Plan.getServerUUID().toString());
statement.addBatch();
}
statement.executeBatch();
commit(statement.getConnection());
} finally {
close(statement);

View File

@ -1,15 +1,7 @@
package main.java.com.djrapitops.plan.systems.cache;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* This Class contains the Cache.
@ -26,15 +18,6 @@ public class DataCache extends SessionCache {
private final Database db;
//Cache
private Map<String, Integer> commandUse;
// Queues
// Variables
private boolean periodicTaskIsSaving = false;
/**
* Class Constructor.
* <p>
@ -46,92 +29,6 @@ public class DataCache extends SessionCache {
public DataCache(Plan plugin) {
super(plugin); // Initializes Session & Location cache.
db = plugin.getDB();
commandUse = new HashMap<>();
if (!getCommandUseFromDb()) {
Log.error(Locale.get(Msg.ENABLE_DB_FAIL_DISABLE_INFO).toString());
plugin.disablePlugin();
return;
}
startAsyncPeriodicSaveTask();
}
/**
* Used to get the initial commandUse Map from the database.
*
* @return Was the fetch successful?
*/
public boolean getCommandUseFromDb() {
try {
commandUse = db.getCommandUse();
return true;
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
}
return false;
}
/**
* Used to start the Asynchronous Save Task.
*
* @throws IllegalArgumentException BukkitRunnable was given wrong
* parameters.
* @throws IllegalStateException BukkitScheduler is in a wrong state.
*/
public void startAsyncPeriodicSaveTask() {
DataCache dataCache = this;
plugin.getRunnableFactory().createNew(new AbsRunnable("PeriodicCacheSaveTask") {
private int timesSaved = 0;
@Override
public void run() {
if (periodicTaskIsSaving) {
return;
}
try {
periodicTaskIsSaving = true;
Log.debug("Database", "Periodic Cache Save");
saveCommandUse();
timesSaved++;
} catch (Exception e) {
Log.toLog(this.getClass().getName() + "(" + this.getName() + ")", e);
} finally {
periodicTaskIsSaving = false;
}
}
}).runTaskTimerAsynchronously(60L * 20L * 5, 60L * 20L * 5);
}
/**
* Saves the cached CommandUse.
* <p>
* Should be only called from an Asynchronous Thread.
*/
public void saveCommandUse() {
try {
db.saveCommandUse(new HashMap<>(commandUse));
} catch (SQLException | NullPointerException e) {
Log.toLog(this.getClass().getName(), e);
}
}
/**
* Used to get the cached commandUse.
*
* @return Map with key:value - "/command":4
*/
public Map<String, Integer> getCommandUse() {
return commandUse;
}
/**
* Used to handle a command's execution.
*
* @param command "/command"
*/
public void handleCommand(String command) {
int amount = commandUse.getOrDefault(command, 0);
commandUse.put(command, amount + 1);
}
}

View File

@ -3,7 +3,7 @@ package main.java.com.djrapitops.plan.systems.listeners;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.systems.cache.DataCache;
import main.java.com.djrapitops.plan.systems.processing.CommandProcessor;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -19,7 +19,6 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class PlanCommandPreprocessListener implements Listener {
private final Plan plugin;
private final DataCache dataCache;
/**
* Class Constructor.
@ -28,7 +27,6 @@ public class PlanCommandPreprocessListener implements Listener {
*/
public PlanCommandPreprocessListener(Plan plugin) {
this.plugin = plugin;
dataCache = plugin.getDataCache();
}
/**
@ -61,7 +59,6 @@ public class PlanCommandPreprocessListener implements Listener {
commandName = command.getName();
}
}
// TODO Command Usage -> DB Save Processor
dataCache.handleCommand(commandName);
plugin.addToProcessQueue(new CommandProcessor(commandName));
}
}

View File

@ -0,0 +1,31 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.systems.processing;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import java.sql.SQLException;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class CommandProcessor extends Processor<String> {
public CommandProcessor(String object) {
super(object);
}
@Override
public void process() {
try {
Plan.getInstance().getDB().getCommandUseTable().commandUsed(object);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -66,16 +66,16 @@ public class ManageUtils {
* @return success?
*/
public static boolean clearAndCopy(Database clearAndCopyToDB, Database copyFromDB) {
try {
// try {
clearAndCopyToDB.removeAllData();
//TODO List<UserInfo> allUserData = copyFromDB.getUserDataForUUIDS(copyFromDB.getSavedUUIDs());
// clearAndCopyToDB.saveMultipleUserData(allUserData);
clearAndCopyToDB.getCommandUseTable().saveCommandUse(copyFromDB.getCommandUseTable().getCommandUse());
// TODO clearAndCopyToDB.getCommandUseTable().saveCommandUse(copyFromDB.getCommandUseTable().getCommandUse());
//TODO clearAndCopyToDB.getTpsTable().saveTPSData(copyFromDB.getTpsTable().getTPSData());
} catch (SQLException | NullPointerException e) {
Log.toLog("ManageUtils.move", e);
return false;
}
// } catch (SQLException | NullPointerException e) {
// Log.toLog("ManageUtils.move", e);
// return false;
// }
return true;
}

View File

@ -109,7 +109,7 @@ public class Analysis {
// List<UUID> uuids = rawData.stream().map(UserInfo::getUuid).collect(Collectors.toList());
Benchmark.start("Create Empty dataset");
DataCache dataCache = plugin.getDataCache();
Map<String, Integer> commandUse = dataCache.getCommandUse();
Map<String, Integer> commandUse = plugin.getDB().getCommandUse();
AnalysisData analysisData = new AnalysisData(commandUse, tpsData);
analysisData.setPluginsTabLayout(plugin.getHookHandler().getPluginsTabLayoutForAnalysis());

View File

@ -47,11 +47,7 @@ public class QueueTest {
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
db.init();
when(plan.getDB()).thenReturn(db);
dataCache = new DataCache(plan) {
@Override
public void startAsyncPeriodicSaveTask() {
}
};
dataCache = new DataCache(plan);
when(plan.getDataCache()).thenReturn(dataCache);
}

View File

@ -21,7 +21,6 @@ import test.java.utils.TestInit;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import static junit.framework.TestCase.assertFalse;
@ -78,15 +77,6 @@ public class DatabaseCommitTest {
@Test
public void testCommitToDBFile() throws SQLException {
db.init();
HashMap<String, Integer> c = new HashMap<>();
c.put("/plan", 1);
c.put("/tp", 4);
c.put("/pla", 7);
c.put("/help", 21);
db.saveCommandUse(c);
db.close();
db.init();
assertFalse(db.getCommandUse().isEmpty());
}
@Ignore("//TODO")

View File

@ -110,28 +110,41 @@ public class DatabaseTest {
@Test
public void testSaveCommandUse() throws SQLException {
CommandUseTable commandUseTable = db.getCommandUseTable();
Map<String, Integer> expected = new HashMap<>();
expected.put("plan", 1);
expected.put("tp", 4);
expected.put("pla", 7);
expected.put("help", 21);
expected.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(expected);
commandUseTable.commandUsed("plan");
for (int i = 0; i < 4; i++) {
commandUseTable.commandUsed("tp");
}
for (int i = 0; i < 7; i++) {
commandUseTable.commandUsed("pla");
}
for (int i = 0; i < 21; i++) {
commandUseTable.commandUsed("help");
}
for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg");
}
expected.remove("roiergbnougbierubieugbeigubeigubgierbgeugeg");
Map<String, Integer> commandUse = db.getCommandUse();
assertEquals(expected, commandUse);
for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("test");
}
for (int i = 0; i < 2; i++) {
commandUseTable.commandUsed("tp");
}
expected.put("test", 3);
expected.put("tp", 6);
expected.put("pla", 4);
db.saveCommandUse(expected);
expected.put("pla", 7);
commandUse = db.getCommandUse();
@ -140,15 +153,20 @@ public class DatabaseTest {
@Test
public void testCommandUseTableIDSystem() throws SQLException {
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
save.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(save);
CommandUseTable commandUseTable = db.getCommandUseTable();
commandUseTable.commandUsed("plan");
for (int i = 0; i < 4; i++) {
commandUseTable.commandUsed("tp");
}
for (int i = 0; i < 7; i++) {
commandUseTable.commandUsed("pla");
}
for (int i = 0; i < 21; i++) {
commandUseTable.commandUsed("help");
}
for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg");
}
Optional<Integer> id = commandUseTable.getCommandID("plan");
assertTrue(id.isPresent());
Optional<String> commandByID = commandUseTable.getCommandByID(id.get());
@ -532,12 +550,12 @@ public class DatabaseTest {
assertTrue(usersTable.isRegistered(uuid));
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
db.saveCommandUse(save);
db.getCommandUseTable().commandUsed("plan");
db.getCommandUseTable().commandUsed("plan");
db.getCommandUseTable().commandUsed("tp");
db.getCommandUseTable().commandUsed("help");
db.getCommandUseTable().commandUsed("help");
db.getCommandUseTable().commandUsed("help");
TPSTable tpsTable = db.getTpsTable();
List<TPS> expected = new ArrayList<>();