Skip to content

Commit

Permalink
Replace database executor with hikari's impl (Fixes #203)
Browse files Browse the repository at this point in the history
  • Loading branch information
games647 committed Jul 21, 2017
1 parent 9e0ab75 commit 8ad4dee
Show file tree
Hide file tree
Showing 14 changed files with 32 additions and 97 deletions.
48 changes: 4 additions & 44 deletions pom.xml
Expand Up @@ -10,35 +10,14 @@
<name>ScoreboardStats</name>
<inceptionYear>2013</inceptionYear>
<description>Show the Scoreboard with many custom variables</description>
<version>0.10.1</version>
<url>http://dev.bukkit.org/bukkit-plugins/scoreboardstats</url>
<version>0.10.3</version>
<url>https://dev.bukkit.org/bukkit-plugins/scoreboardstats</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<powermock.version>1.7.0</powermock.version>
<!--Possibility to deploy directly to the plugins folder-->
<outputDir>${basedir}/target</outputDir>
</properties>

<issueManagement>
<system>GitHub</system>
<url>https://github.com/games647/ScoreboardStats/issues</url>
</issueManagement>

<scm>
<url>https://github.com/games647/ScoreboardStats</url>
<connection>scm:git:git://github.com/games647/ScoreboardStats.git</connection>
<developerConnection>scm:git:ssh://git@github.com:games647/ScoreboardStats.git</developerConnection>
</scm>

<licenses>
<license>
<name>The MIT License</name>
<url>http://opensource.org/licenses/MIT</url>
<distribution>repo</distribution>
</license>
</licenses>

<build>
<defaultGoal>install</defaultGoal>
<!--Just use the project name to replace an old version of the plugin if the user does only copy-paste-->
Expand All @@ -52,17 +31,6 @@
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<outputDirectory>${outputDir}</outputDirectory>
</configuration>
</plugin>

Expand Down Expand Up @@ -100,14 +68,6 @@
<!--Replace variables-->
<filtering>true</filtering>
</resource>

<!--Add the license to jar in order to see it in the final jar-->
<resource>
<directory>${basedir}</directory>
<includes>
<include>LICENSE</include>
</includes>
</resource>
</resources>
</build>

Expand All @@ -121,7 +81,7 @@
<!--mcmmo-->
<repository>
<id>md_5-releases</id>
<url>http://repo.md-5.net/content/groups/public/</url>
<url>https://repo.md-5.net/content/groups/public/</url>
</repository>

<!--Vault and Heroes-->
Expand Down Expand Up @@ -174,7 +134,7 @@
<repository>
<id>bintray-tastybento-maven-repo</id>
<name>bintray</name>
<url>http://dl.bintray.com/tastybento/maven-repo</url>
<url>https://dl.bintray.com/tastybento/maven-repo</url>
</repository>

<!--MyPet-->
Expand Down
Expand Up @@ -39,16 +39,16 @@ public void run() {
int remainingUpdates = getNextUpdates();
for (Map.Entry<Player, MutableInt> entry : queue.entrySet()) {
Player player = entry.getKey();
MutableInt remanigTicks = entry.getValue();
if (remanigTicks.intValue() == 0) {
MutableInt remainingTicks = entry.getValue();
if (remainingTicks.intValue() == 0) {
if (remainingUpdates != 0) {
//Smoother refreshing; limit the updates
plugin.getScoreboardManager().onUpdate(player);
remanigTicks.setValue(20 * Settings.getInterval());
remainingTicks.setValue(20 * Settings.getInterval());
remainingUpdates--;
}
} else {
remanigTicks.decrement();
remainingTicks.decrement();
}
}

Expand Down
Expand Up @@ -6,7 +6,6 @@
import com.google.common.collect.Maps;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -78,7 +77,7 @@ public List<String> onTabComplete(CommandSender sender, Command command, String
suggestion = commandHandler.onTabComplete(sender, subCommand, Arrays.copyOfRange(args, 1, args.length));
if (suggestion != null) {
//Prevent NPEs and the usage of this method in nearly every handler
Collections.sort(suggestion, String.CASE_INSENSITIVE_ORDER);
suggestion.sort(String.CASE_INSENSITIVE_ORDER);
}

return suggestion;
Expand Down
Expand Up @@ -6,7 +6,6 @@
import com.github.games647.scoreboardstats.config.Settings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
Expand All @@ -21,10 +20,7 @@
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
Expand All @@ -42,8 +38,6 @@ public class Database {

private final ScoreboardStats plugin;

private final ScheduledExecutorService executor;

private final Map<String, Integer> toplist = Maps.newHashMapWithExpectedSize(Settings.getTopitems());

private final DatabaseConfiguration dbConfig;
Expand All @@ -52,11 +46,6 @@ public class Database {
public Database(ScoreboardStats plugin) {
this.plugin = plugin;
this.dbConfig = new DatabaseConfiguration(plugin);

//SQL transactions are mainly blocking so there is no need to update them smooth
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
//Give the thread a name so we can find them
.setNameFormat(plugin.getName() + "-Database").build());
}

/**
Expand Down Expand Up @@ -84,7 +73,8 @@ public PlayerStats getCachedStats(Player request) {
*/
public void loadAccountAsync(Player player) {
if (getCachedStats(player) == null && dataSource != null) {
executor.execute(new StatsLoader(plugin, dbConfig.isUuidUse(), player, this));
Runnable statsLoader = new StatsLoader(plugin, dbConfig.isUuidUse(), player, this);
Bukkit.getScheduler().runTaskAsynchronously(plugin, statsLoader);
}
}

Expand Down Expand Up @@ -172,7 +162,7 @@ public PlayerStats loadAccount(Player player) {
* @param stats PlayerStats data
*/
public void saveAsync(PlayerStats stats) {
executor.submit(() -> save(Lists.newArrayList(stats)));
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> save(Lists.newArrayList(stats)));
}

/**
Expand Down Expand Up @@ -291,15 +281,10 @@ public void saveAll() {
save(toSave);
}

executor.shutdown();

executor.awaitTermination(15, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
plugin.getLogger().log(Level.SEVERE, "Couldn't save the stats to the database", ex);
dataSource.close();
} finally {
//Make rally sure we remove all even on error
BackwardsCompatibleUtil.getOnlinePlayers()
.stream()
.forEach(player -> player.removeMetadata(METAKEY, plugin));
}
}
Expand Down Expand Up @@ -340,9 +325,8 @@ public void setupDatabase() {
close(conn);
}

executor.scheduleWithFixedDelay(this::updateTopList, 0, 5, TimeUnit.MINUTES);

executor.scheduleWithFixedDelay(() -> {
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this::updateTopList, 20 * 60 * 5, 0);
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> {
if (dataSource == null) {
return;
}
Expand All @@ -367,7 +351,7 @@ public void setupDatabase() {
} catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE, null, ex);
}
}, 0, 1, TimeUnit.MINUTES);
}, 20 * 60, 0);

registerEvents();
}
Expand Down
Expand Up @@ -128,7 +128,7 @@ public void createTopListScoreboard(Player player) {
objective.setDisplayName(Settings.getTempTitle());

//Colorize and send all elements
plugin.getStatsDatabase().getTop().stream().forEach((entry) -> {
plugin.getStatsDatabase().getTop().forEach((entry) -> {
String scoreName = stripLength(Settings.getTempColor() + entry.getKey());
sendScore(objective, scoreName, entry.getValue(), true);
});
Expand Down
Expand Up @@ -35,7 +35,7 @@ public class PacketListener extends PacketAdapter {
/**
* Creates a new packet listener
*
* @param plugin plugin for registration into ProtcolLib
* @param plugin plugin for registration into ProtocolLib
* @param manager packet manager instance
*/
public PacketListener(Plugin plugin, PacketSbManager manager) {
Expand Down
Expand Up @@ -41,9 +41,8 @@ public PacketSbManager(ScoreboardStats plugin) {
* @return the scoreboard instance
*/
public PlayerScoreboard getScoreboard(Player player) {
PlayerScoreboard scoreboard = scoreboards
return scoreboards
.computeIfAbsent(player.getUniqueId(), key -> new PlayerScoreboard(player));
return scoreboard;
}

@Override
Expand Down
Expand Up @@ -57,7 +57,7 @@ public Objective createSidebarObjective(String objectiveName, String displayName
}

if (objectivesByName.containsKey(objectiveName)) {
//the objecive already exits. I assume that no other use this unique name
//the objective already exits. I assume that no other use this unique name
//so we expect that a other sidebar was showing
Objective objective = objectivesByName.get(objectiveName);
PacketFactory.sendDisplayPacket(objective);
Expand Down Expand Up @@ -130,7 +130,7 @@ void resetScore(String scoreName) {
* Very weird that minecraft always ignore the name of the parent objective and
* will remove the score from the complete scoreboard
*/
objectivesByName.values().stream().forEach(entry -> entry.items.remove(scoreName));
objectivesByName.values().forEach(entry -> entry.items.remove(scoreName));
}

void createOrUpdateScore(String scoreName, String parent, int score) {
Expand Down
Expand Up @@ -31,7 +31,7 @@ public void onPluginEnable(PluginEnableEvent enableEvent) {
//Register the listener back again if the plugin is available
String enablePluginName = enableEvent.getPlugin().getName();
Map<Class<? extends VariableReplaceAdapter<?>>, String> defaults = replaceManager.getDefaults();
defaults.entrySet().stream().forEach(entry -> {
defaults.entrySet().forEach(entry -> {
String pluginName = entry.getValue();
if (enablePluginName.equals(entry.getValue())) {
replaceManager.registerDefault(entry.getKey(), pluginName);
Expand Down
Expand Up @@ -7,6 +7,7 @@
*
* @deprecated not fully featured and returns magic values. Will be removed in future versions
*/
@FunctionalInterface
@Deprecated
public interface Replaceable {

Expand Down
Expand Up @@ -31,7 +31,7 @@ private static String[] getSkillVariables() {
.map(String::toLowerCase).collect(Collectors.toSet());

skills.add("powlvl");
return skills.stream().toArray(String[]::new);
return skills.toArray(new String[0]);
}

private final ReplaceManager replaceManager;
Expand Down
Expand Up @@ -36,7 +36,7 @@ private static String[] getVariablesPrefixes() {
}
}

return variables.stream().toArray(String[]::new);
return variables.toArray(new String[0]);
}

public PlaceHolderVariables() {
Expand Down
Expand Up @@ -6,7 +6,6 @@
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.messaging.StandardMessenger;
Expand Down Expand Up @@ -39,15 +38,11 @@ public void getVariable() throws UnknownVariableException {
Mockito.when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger());

ReplaceManager replaceManager = new ReplaceManager(null, plugin);
replaceManager.register(new Replaceable() {

@Override
public int getScoreValue(Player player, String variable) {
Logger.getAnonymousLogger().log(Level.INFO, "Replaced variable: {0}", variable);
Assert.assertTrue(variable.charAt(0) == '%');
Assert.assertTrue(variable.endsWith("%"));
return 0;
}
replaceManager.register((player, variable) -> {
Logger.getAnonymousLogger().log(Level.INFO, "Replaced variable: {0}", variable);
Assert.assertTrue(variable.charAt(0) == '%');
Assert.assertTrue(variable.endsWith("%"));
return 0;
}, "pluginName");

replaceManager.getScore(null, "variableName", "test", -1, true);
Expand Down
Expand Up @@ -55,11 +55,8 @@ public void onReplace(Player player, String variable, ReplaceEvent replaceEvent)

@SuppressWarnings("deprecation")
private void testLegacy(ReplaceManager replaceManager) {
Replaceable legacyReplaceable = new Replaceable() {
@Override
public int getScoreValue(Player player, String variable) {
throw new UnsupportedOperationException("Not supported yet.");
}
Replaceable legacyReplaceable = (player, variable) -> {
throw new UnsupportedOperationException("Not supported yet.");
};

LegacyReplaceWrapper legacyWrapper = new LegacyReplaceWrapper(Bukkit
Expand Down

0 comments on commit 8ad4dee

Please sign in to comment.