propagate i/o errors to the futures returned by the dao

This commit is contained in:
Luck 2017-12-10 01:47:00 +00:00
parent 9dd4f71526
commit 322b522a52
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
13 changed files with 408 additions and 529 deletions

View File

@ -299,17 +299,21 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
// Load any online users (in the case of a reload) // Load any online users (in the case of a reload)
for (Player player : getServer().getOnlinePlayers()) { for (Player player : getServer().getOnlinePlayers()) {
scheduler.doAsync(() -> { scheduler.doAsync(() -> {
LoginHelper.loadUser(this, player.getUniqueId(), player.getName(), false); try {
User user = getUserManager().getIfLoaded(getUuidCache().getUUID(player.getUniqueId())); LoginHelper.loadUser(this, player.getUniqueId(), player.getName(), false);
if (user != null) { User user = getUserManager().getIfLoaded(getUuidCache().getUUID(player.getUniqueId()));
scheduler.doSync(() -> { if (user != null) {
try { scheduler.doSync(() -> {
LPPermissible lpPermissible = new LPPermissible(player, user, this); try {
PermissibleInjector.inject(player, lpPermissible); LPPermissible lpPermissible = new LPPermissible(player, user, this);
} catch (Throwable t) { PermissibleInjector.inject(player, lpPermissible);
t.printStackTrace(); } catch (Throwable t) {
} t.printStackTrace();
}); }
});
}
} catch (Exception e) {
e.printStackTrace();
} }
}); });
} }

View File

@ -323,7 +323,7 @@ data:
# This setting controls the maximum number of milliseconds that the plugin will wait for a # This setting controls the maximum number of milliseconds that the plugin will wait for a
# connection from the pool, before timing out. # connection from the pool, before timing out.
connection-timeout: 15000 # 15 seconds connection-timeout: 5000 # 5 seconds
# This setting allows you to define extra properties for connections. # This setting allows you to define extra properties for connections.
properties: properties:

View File

@ -269,7 +269,7 @@ data:
# This setting controls the maximum number of milliseconds that the plugin will wait for a # This setting controls the maximum number of milliseconds that the plugin will wait for a
# connection from the pool, before timing out. # connection from the pool, before timing out.
connection-timeout: 15000 # 15 seconds connection-timeout: 5000 # 5 seconds
# This setting allows you to define extra properties for connections. # This setting allows you to define extra properties for connections.
properties: properties:

View File

@ -367,7 +367,7 @@ public class ConfigKeys {
int maxPoolSize = c.getInt("data.pool-settings.maximum-pool-size", c.getInt("data.pool-size", 10)); int maxPoolSize = c.getInt("data.pool-settings.maximum-pool-size", c.getInt("data.pool-size", 10));
int minIdle = c.getInt("data.pool-settings.minimum-idle", maxPoolSize); int minIdle = c.getInt("data.pool-settings.minimum-idle", maxPoolSize);
int maxLifetime = c.getInt("data.pool-settings.maximum-lifetime", 1800000); int maxLifetime = c.getInt("data.pool-settings.maximum-lifetime", 1800000);
int connectionTimeout = c.getInt("data.pool-settings.connection-timeout", 15000); int connectionTimeout = c.getInt("data.pool-settings.connection-timeout", 5000);
Map<String, String> props = ImmutableMap.copyOf(c.getMap("data.pool-settings.properties", ImmutableMap.of("useUnicode", "true", "characterEncoding", "utf8"))); Map<String, String> props = ImmutableMap.copyOf(c.getMap("data.pool-settings.properties", ImmutableMap.of("useUnicode", "true", "characterEncoding", "utf8")));
return new StorageCredentials( return new StorageCredentials(

View File

@ -46,6 +46,7 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -86,7 +87,7 @@ public class DependencyManager {
public DependencyManager(LuckPermsPlugin plugin) { public DependencyManager(LuckPermsPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
try { try {
this.digest = MessageDigest.getInstance("SHA-1"); this.digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -168,8 +169,11 @@ public class DependencyManager {
} }
byte[] hash = this.digest.digest(bytes); byte[] hash = this.digest.digest(bytes);
plugin.getLog().info("Successfully downloaded '" + fileName + "' with checksum: " + Base64.getEncoder().encodeToString(hash));
if (!Arrays.equals(hash, dependency.getChecksum())) { if (!Arrays.equals(hash, dependency.getChecksum())) {
throw new RuntimeException("Downloaded file had an invalid hash."); throw new RuntimeException("Downloaded file had an invalid hash. Expected: " + Base64.getEncoder().encodeToString(dependency.getChecksum()));
} }
Files.write(file.toPath(), bytes); Files.write(file.toPath(), bytes);
@ -178,7 +182,6 @@ public class DependencyManager {
if (!file.exists()) { if (!file.exists()) {
throw new IllegalStateException("File not present. - " + file.toString()); throw new IllegalStateException("File not present. - " + file.toString());
} else { } else {
plugin.getLog().info("Dependency '" + fileName + "' successfully downloaded.");
return file; return file;
} }
} }

View File

@ -29,6 +29,8 @@ import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import com.google.common.base.Throwables;
import me.lucko.luckperms.api.HeldPermission; import me.lucko.luckperms.api.HeldPermission;
import me.lucko.luckperms.api.LogEntry; import me.lucko.luckperms.api.LogEntry;
import me.lucko.luckperms.api.event.cause.CreationCause; import me.lucko.luckperms.api.event.cause.CreationCause;
@ -48,8 +50,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier; import java.util.concurrent.CompletionException;
/** /**
* Converts a {@link AbstractDao} to use {@link CompletableFuture}s * Converts a {@link AbstractDao} to use {@link CompletableFuture}s
@ -74,8 +77,15 @@ public class AbstractStorage implements Storage {
this.delegate = new ApiStorage(plugin, this); this.delegate = new ApiStorage(plugin, this);
} }
private <T> CompletableFuture<T> makeFuture(Supplier<T> supplier) { private <T> CompletableFuture<T> makeFuture(Callable<T> supplier) {
return CompletableFuture.supplyAsync(supplier, dao.getPlugin().getScheduler().async()); return CompletableFuture.supplyAsync(() -> {
try {
return supplier.call();
} catch (Exception e) {
Throwables.propagateIfPossible(e);
throw new CompletionException(e);
}
}, dao.getPlugin().getScheduler().async());
} }
@Override @Override

View File

@ -61,46 +61,46 @@ public abstract class AbstractDao {
return Collections.emptyMap(); return Collections.emptyMap();
} }
public abstract boolean logAction(LogEntry entry); public abstract boolean logAction(LogEntry entry) throws Exception;
public abstract Log getLog(); public abstract Log getLog() throws Exception;
public abstract boolean applyBulkUpdate(BulkUpdate bulkUpdate); public abstract boolean applyBulkUpdate(BulkUpdate bulkUpdate) throws Exception;
public abstract boolean loadUser(UUID uuid, String username); public abstract boolean loadUser(UUID uuid, String username) throws Exception;
public abstract boolean saveUser(User user); public abstract boolean saveUser(User user) throws Exception;
public abstract Set<UUID> getUniqueUsers(); public abstract Set<UUID> getUniqueUsers() throws Exception;
public abstract List<HeldPermission<UUID>> getUsersWithPermission(String permission); public abstract List<HeldPermission<UUID>> getUsersWithPermission(String permission) throws Exception;
public abstract boolean createAndLoadGroup(String name); public abstract boolean createAndLoadGroup(String name) throws Exception;
public abstract boolean loadGroup(String name); public abstract boolean loadGroup(String name) throws Exception;
public abstract boolean loadAllGroups(); public abstract boolean loadAllGroups() throws Exception;
public abstract boolean saveGroup(Group group); public abstract boolean saveGroup(Group group) throws Exception;
public abstract boolean deleteGroup(Group group); public abstract boolean deleteGroup(Group group) throws Exception;
public abstract List<HeldPermission<String>> getGroupsWithPermission(String permission); public abstract List<HeldPermission<String>> getGroupsWithPermission(String permission) throws Exception;
public abstract boolean createAndLoadTrack(String name); public abstract boolean createAndLoadTrack(String name) throws Exception;
public abstract boolean loadTrack(String name); public abstract boolean loadTrack(String name) throws Exception;
public abstract boolean loadAllTracks(); public abstract boolean loadAllTracks() throws Exception;
public abstract boolean saveTrack(Track track); public abstract boolean saveTrack(Track track) throws Exception;
public abstract boolean deleteTrack(Track track); public abstract boolean deleteTrack(Track track) throws Exception;
public abstract boolean saveUUIDData(UUID uuid, String username); public abstract boolean saveUUIDData(UUID uuid, String username) throws Exception;
public abstract UUID getUUID(String username); public abstract UUID getUUID(String username) throws Exception;
public abstract String getName(UUID uuid); public abstract String getName(UUID uuid) throws Exception;
} }

View File

@ -70,7 +70,13 @@ public class SplitStorageDao extends AbstractDao {
@Override @Override
public void shutdown() { public void shutdown() {
backing.values().forEach(AbstractDao::shutdown); for (AbstractDao ds : backing.values()) {
try {
ds.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
} }
@Override @Override
@ -84,17 +90,17 @@ public class SplitStorageDao extends AbstractDao {
} }
@Override @Override
public boolean logAction(LogEntry entry) { public boolean logAction(LogEntry entry) throws Exception {
return backing.get(types.get("log")).logAction(entry); return backing.get(types.get("log")).logAction(entry);
} }
@Override @Override
public Log getLog() { public Log getLog() throws Exception {
return backing.get(types.get("log")).getLog(); return backing.get(types.get("log")).getLog();
} }
@Override @Override
public boolean applyBulkUpdate(BulkUpdate bulkUpdate) { public boolean applyBulkUpdate(BulkUpdate bulkUpdate) throws Exception {
String userType = types.get("user"); String userType = types.get("user");
String groupType = types.get("group"); String groupType = types.get("group");
@ -108,92 +114,92 @@ public class SplitStorageDao extends AbstractDao {
} }
@Override @Override
public boolean loadUser(UUID uuid, String username) { public boolean loadUser(UUID uuid, String username) throws Exception {
return backing.get(types.get("user")).loadUser(uuid, username); return backing.get(types.get("user")).loadUser(uuid, username);
} }
@Override @Override
public boolean saveUser(User user) { public boolean saveUser(User user) throws Exception {
return backing.get(types.get("user")).saveUser(user); return backing.get(types.get("user")).saveUser(user);
} }
@Override @Override
public Set<UUID> getUniqueUsers() { public Set<UUID> getUniqueUsers() throws Exception {
return backing.get(types.get("user")).getUniqueUsers(); return backing.get(types.get("user")).getUniqueUsers();
} }
@Override @Override
public List<HeldPermission<UUID>> getUsersWithPermission(String permission) { public List<HeldPermission<UUID>> getUsersWithPermission(String permission) throws Exception {
return backing.get(types.get("user")).getUsersWithPermission(permission); return backing.get(types.get("user")).getUsersWithPermission(permission);
} }
@Override @Override
public boolean createAndLoadGroup(String name) { public boolean createAndLoadGroup(String name) throws Exception {
return backing.get(types.get("group")).createAndLoadGroup(name); return backing.get(types.get("group")).createAndLoadGroup(name);
} }
@Override @Override
public boolean loadGroup(String name) { public boolean loadGroup(String name) throws Exception {
return backing.get(types.get("group")).loadGroup(name); return backing.get(types.get("group")).loadGroup(name);
} }
@Override @Override
public boolean loadAllGroups() { public boolean loadAllGroups() throws Exception {
return backing.get(types.get("group")).loadAllGroups(); return backing.get(types.get("group")).loadAllGroups();
} }
@Override @Override
public boolean saveGroup(Group group) { public boolean saveGroup(Group group) throws Exception {
return backing.get(types.get("group")).saveGroup(group); return backing.get(types.get("group")).saveGroup(group);
} }
@Override @Override
public boolean deleteGroup(Group group) { public boolean deleteGroup(Group group) throws Exception {
return backing.get(types.get("group")).deleteGroup(group); return backing.get(types.get("group")).deleteGroup(group);
} }
@Override @Override
public List<HeldPermission<String>> getGroupsWithPermission(String permission) { public List<HeldPermission<String>> getGroupsWithPermission(String permission) throws Exception {
return backing.get(types.get("group")).getGroupsWithPermission(permission); return backing.get(types.get("group")).getGroupsWithPermission(permission);
} }
@Override @Override
public boolean createAndLoadTrack(String name) { public boolean createAndLoadTrack(String name) throws Exception {
return backing.get(types.get("track")).createAndLoadTrack(name); return backing.get(types.get("track")).createAndLoadTrack(name);
} }
@Override @Override
public boolean loadTrack(String name) { public boolean loadTrack(String name) throws Exception {
return backing.get(types.get("track")).loadTrack(name); return backing.get(types.get("track")).loadTrack(name);
} }
@Override @Override
public boolean loadAllTracks() { public boolean loadAllTracks() throws Exception {
return backing.get(types.get("track")).loadAllTracks(); return backing.get(types.get("track")).loadAllTracks();
} }
@Override @Override
public boolean saveTrack(Track track) { public boolean saveTrack(Track track) throws Exception {
return backing.get(types.get("track")).saveTrack(track); return backing.get(types.get("track")).saveTrack(track);
} }
@Override @Override
public boolean deleteTrack(Track track) { public boolean deleteTrack(Track track) throws Exception {
return backing.get(types.get("track")).deleteTrack(track); return backing.get(types.get("track")).deleteTrack(track);
} }
@Override @Override
public boolean saveUUIDData(UUID uuid, String username) { public boolean saveUUIDData(UUID uuid, String username) throws Exception {
return backing.get(types.get("uuid")).saveUUIDData(uuid, username); return backing.get(types.get("uuid")).saveUUIDData(uuid, username);
} }
@Override @Override
public UUID getUUID(String username) { public UUID getUUID(String username) throws Exception {
return backing.get(types.get("uuid")).getUUID(username); return backing.get(types.get("uuid")).getUUID(username);
} }
@Override @Override
public String getName(UUID uuid) { public String getName(UUID uuid) throws Exception {
return backing.get(types.get("uuid")).getName(uuid); return backing.get(types.get("uuid")).getName(uuid);
} }
} }

View File

@ -156,10 +156,10 @@ public abstract class ConfigurateDao extends AbstractDao {
return (dir, name) -> name.endsWith(fileExtension); return (dir, name) -> name.endsWith(fileExtension);
} }
private boolean reportException(String file, Exception ex) { private Exception reportException(String file, Exception ex) throws Exception {
plugin.getLog().warn("Exception thrown whilst performing i/o: " + file); plugin.getLog().warn("Exception thrown whilst performing i/o: " + file);
ex.printStackTrace(); ex.printStackTrace();
return false; throw ex;
} }
private void registerFileAction(StorageLocation type, File file) { private void registerFileAction(StorageLocation type, File file) {
@ -322,68 +322,63 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean applyBulkUpdate(BulkUpdate bulkUpdate) { public boolean applyBulkUpdate(BulkUpdate bulkUpdate) throws Exception {
try { if (bulkUpdate.getDataType().isIncludingUsers()) {
if (bulkUpdate.getDataType().isIncludingUsers()) { File[] files = getDirectory(StorageLocation.USER).listFiles(getFileTypeFilter());
File[] files = getDirectory(StorageLocation.USER).listFiles(getFileTypeFilter()); if (files == null) {
if (files == null) { throw new IllegalStateException("Users directory matched no files.");
throw new IllegalStateException("Users directory matched no files.");
}
for (File file : files) {
try {
registerFileAction(StorageLocation.USER, file);
ConfigurationNode object = readFile(file);
Set<NodeModel> nodes = readNodes(object);
Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!nodes.equals(results)) {
writeNodes(object, results);
saveFile(file, object);
}
} catch (Exception e) {
reportException(file.getName(), e);
}
}
} }
if (bulkUpdate.getDataType().isIncludingGroups()) { for (File file : files) {
File[] files = getDirectory(StorageLocation.GROUP).listFiles(getFileTypeFilter()); try {
if (files == null) { registerFileAction(StorageLocation.USER, file);
throw new IllegalStateException("Groups directory matched no files."); ConfigurationNode object = readFile(file);
} Set<NodeModel> nodes = readNodes(object);
Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for (File file : files) { if (!nodes.equals(results)) {
try { writeNodes(object, results);
registerFileAction(StorageLocation.GROUP, file); saveFile(file, object);
ConfigurationNode object = readFile(file);
Set<NodeModel> nodes = readNodes(object);
Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!nodes.equals(results)) {
writeNodes(object, results);
saveFile(file, object);
}
} catch (Exception e) {
reportException(file.getName(), e);
} }
} catch (Exception e) {
throw reportException(file.getName(), e);
}
}
}
if (bulkUpdate.getDataType().isIncludingGroups()) {
File[] files = getDirectory(StorageLocation.GROUP).listFiles(getFileTypeFilter());
if (files == null) {
throw new IllegalStateException("Groups directory matched no files.");
}
for (File file : files) {
try {
registerFileAction(StorageLocation.GROUP, file);
ConfigurationNode object = readFile(file);
Set<NodeModel> nodes = readNodes(object);
Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!nodes.equals(results)) {
writeNodes(object, results);
saveFile(file, object);
}
} catch (Exception e) {
throw reportException(file.getName(), e);
} }
} }
} catch (Exception e) {
reportException("bulk update", e);
return false;
} }
return true; return true;
} }
@Override @Override
public boolean loadUser(UUID uuid, String username) { public boolean loadUser(UUID uuid, String username) throws Exception {
User user = plugin.getUserManager().getOrMake(UserIdentifier.of(uuid, username)); User user = plugin.getUserManager().getOrMake(UserIdentifier.of(uuid, username));
user.getIoLock().lock(); user.getIoLock().lock();
try { try {
@ -412,7 +407,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(uuid.toString(), e); throw reportException(uuid.toString(), e);
} finally { } finally {
user.getIoLock().unlock(); user.getIoLock().unlock();
} }
@ -421,7 +416,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean saveUser(User user) { public boolean saveUser(User user) throws Exception {
user.getIoLock().lock(); user.getIoLock().lock();
try { try {
if (!GenericUserManager.shouldSave(user)) { if (!GenericUserManager.shouldSave(user)) {
@ -438,7 +433,7 @@ public abstract class ConfigurateDao extends AbstractDao {
saveFile(StorageLocation.USER, user.getUuid().toString(), data); saveFile(StorageLocation.USER, user.getUuid().toString(), data);
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(user.getUuid().toString(), e); throw reportException(user.getUuid().toString(), e);
} finally { } finally {
user.getIoLock().unlock(); user.getIoLock().unlock();
} }
@ -456,39 +451,34 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public List<HeldPermission<UUID>> getUsersWithPermission(String permission) { public List<HeldPermission<UUID>> getUsersWithPermission(String permission) throws Exception {
ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder();
try { File[] files = getDirectory(StorageLocation.USER).listFiles(getFileTypeFilter());
File[] files = getDirectory(StorageLocation.USER).listFiles(getFileTypeFilter()); if (files == null) {
if (files == null) { throw new IllegalStateException("Users directory matched no files.");
throw new IllegalStateException("Users directory matched no files."); }
}
for (File file : files) { for (File file : files) {
try { try {
registerFileAction(StorageLocation.USER, file); registerFileAction(StorageLocation.USER, file);
ConfigurationNode object = readFile(file); ConfigurationNode object = readFile(file);
UUID holder = UUID.fromString(file.getName().substring(0, file.getName().length() - fileExtension.length())); UUID holder = UUID.fromString(file.getName().substring(0, file.getName().length() - fileExtension.length()));
Set<NodeModel> nodes = readNodes(object); Set<NodeModel> nodes = readNodes(object);
for (NodeModel e : nodes) { for (NodeModel e : nodes) {
if (!e.getPermission().equalsIgnoreCase(permission)) { if (!e.getPermission().equalsIgnoreCase(permission)) {
continue; continue;
}
held.add(NodeHeldPermission.of(holder, e));
} }
} catch (Exception e) { held.add(NodeHeldPermission.of(holder, e));
reportException(file.getName(), e);
} }
} catch (Exception e) {
throw reportException(file.getName(), e);
} }
} catch (Exception e) {
reportException("users", e);
return null;
} }
return held.build(); return held.build();
} }
@Override @Override
public boolean createAndLoadGroup(String name) { public boolean createAndLoadGroup(String name) throws Exception {
Group group = plugin.getGroupManager().getOrMake(name); Group group = plugin.getGroupManager().getOrMake(name);
group.getIoLock().lock(); group.getIoLock().lock();
try { try {
@ -507,7 +497,7 @@ public abstract class ConfigurateDao extends AbstractDao {
saveFile(StorageLocation.GROUP, name, data); saveFile(StorageLocation.GROUP, name, data);
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(name, e); throw reportException(name, e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -516,7 +506,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean loadGroup(String name) { public boolean loadGroup(String name) throws Exception {
Group group = plugin.getGroupManager().getIfLoaded(name); Group group = plugin.getGroupManager().getIfLoaded(name);
if (group != null) { if (group != null) {
group.getIoLock().lock(); group.getIoLock().lock();
@ -539,7 +529,7 @@ public abstract class ConfigurateDao extends AbstractDao {
group.setEnduringNodes(nodes); group.setEnduringNodes(nodes);
} catch (Exception e) { } catch (Exception e) {
return reportException(name, e); throw reportException(name, e);
} finally { } finally {
if (group != null) { if (group != null) {
group.getIoLock().unlock(); group.getIoLock().unlock();
@ -557,17 +547,30 @@ public abstract class ConfigurateDao extends AbstractDao {
.map(s -> s.substring(0, s.length() - fileExtension.length())) .map(s -> s.substring(0, s.length() - fileExtension.length()))
.collect(Collectors.toList()); .collect(Collectors.toList());
groups.forEach(this::loadGroup); boolean success = true;
for (String g : groups) {
try {
loadGroup(g);
} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (!success) {
throw new RuntimeException("Exception occurred whilst loading a group");
}
GroupManager gm = plugin.getGroupManager(); GroupManager gm = plugin.getGroupManager();
gm.getAll().values().stream() gm.getAll().values().stream()
.filter(g -> !groups.contains(g.getName())) .filter(g -> !groups.contains(g.getName()))
.forEach(gm::unload); .forEach(gm::unload);
return true; return true;
} }
@Override @Override
public boolean saveGroup(Group group) { public boolean saveGroup(Group group) throws Exception {
group.getIoLock().lock(); group.getIoLock().lock();
try { try {
ConfigurationNode data = SimpleConfigurationNode.root(); ConfigurationNode data = SimpleConfigurationNode.root();
@ -578,7 +581,7 @@ public abstract class ConfigurateDao extends AbstractDao {
saveFile(StorageLocation.GROUP, group.getName(), data); saveFile(StorageLocation.GROUP, group.getName(), data);
} catch (Exception e) { } catch (Exception e) {
return reportException(group.getName(), e); throw reportException(group.getName(), e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -586,7 +589,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean deleteGroup(Group group) { public boolean deleteGroup(Group group) throws Exception {
group.getIoLock().lock(); group.getIoLock().lock();
try { try {
File groupFile = new File(groupsDirectory, group.getName() + fileExtension); File groupFile = new File(groupsDirectory, group.getName() + fileExtension);
@ -596,7 +599,7 @@ public abstract class ConfigurateDao extends AbstractDao {
groupFile.delete(); groupFile.delete();
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(group.getName(), e); throw reportException(group.getName(), e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -604,39 +607,34 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public List<HeldPermission<String>> getGroupsWithPermission(String permission) { public List<HeldPermission<String>> getGroupsWithPermission(String permission) throws Exception {
ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder();
try { File[] files = getDirectory(StorageLocation.GROUP).listFiles(getFileTypeFilter());
File[] files = getDirectory(StorageLocation.GROUP).listFiles(getFileTypeFilter()); if (files == null) {
if (files == null) { throw new IllegalStateException("Groups directory matched no files.");
throw new IllegalStateException("Groups directory matched no files."); }
}
for (File file : files) { for (File file : files) {
try { try {
registerFileAction(StorageLocation.GROUP, file); registerFileAction(StorageLocation.GROUP, file);
ConfigurationNode object = readFile(file); ConfigurationNode object = readFile(file);
String holder = file.getName().substring(0, file.getName().length() - fileExtension.length()); String holder = file.getName().substring(0, file.getName().length() - fileExtension.length());
Set<NodeModel> nodes = readNodes(object); Set<NodeModel> nodes = readNodes(object);
for (NodeModel e : nodes) { for (NodeModel e : nodes) {
if (!e.getPermission().equalsIgnoreCase(permission)) { if (!e.getPermission().equalsIgnoreCase(permission)) {
continue; continue;
}
held.add(NodeHeldPermission.of(holder, e));
} }
} catch (Exception e) { held.add(NodeHeldPermission.of(holder, e));
reportException(file.getName(), e);
} }
} catch (Exception e) {
throw reportException(file.getName(), e);
} }
} catch (Exception e) {
reportException("groups", e);
return null;
} }
return held.build(); return held.build();
} }
@Override @Override
public boolean createAndLoadTrack(String name) { public boolean createAndLoadTrack(String name) throws Exception {
Track track = plugin.getTrackManager().getOrMake(name); Track track = plugin.getTrackManager().getOrMake(name);
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
@ -656,7 +654,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(name, e); throw reportException(name, e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -664,7 +662,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean loadTrack(String name) { public boolean loadTrack(String name) throws Exception {
Track track = plugin.getTrackManager().getIfLoaded(name); Track track = plugin.getTrackManager().getIfLoaded(name);
if (track != null) { if (track != null) {
track.getIoLock().lock(); track.getIoLock().lock();
@ -689,7 +687,7 @@ public abstract class ConfigurateDao extends AbstractDao {
track.setGroups(groups); track.setGroups(groups);
} catch (Exception e) { } catch (Exception e) {
return reportException(name, e); throw reportException(name, e);
} finally { } finally {
if (track != null) { if (track != null) {
track.getIoLock().unlock(); track.getIoLock().unlock();
@ -706,17 +704,30 @@ public abstract class ConfigurateDao extends AbstractDao {
.map(s -> s.substring(0, s.length() - fileExtension.length())) .map(s -> s.substring(0, s.length() - fileExtension.length()))
.collect(Collectors.toList()); .collect(Collectors.toList());
tracks.forEach(this::loadTrack); boolean success = true;
for (String t : tracks) {
try {
loadTrack(t);
} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (!success) {
throw new RuntimeException("Exception occurred whilst loading a track");
}
TrackManager tm = plugin.getTrackManager(); TrackManager tm = plugin.getTrackManager();
tm.getAll().values().stream() tm.getAll().values().stream()
.filter(t -> !tracks.contains(t.getName())) .filter(t -> !tracks.contains(t.getName()))
.forEach(tm::unload); .forEach(tm::unload);
return true; return true;
} }
@Override @Override
public boolean saveTrack(Track track) { public boolean saveTrack(Track track) throws Exception {
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
ConfigurationNode data = SimpleConfigurationNode.root(); ConfigurationNode data = SimpleConfigurationNode.root();
@ -724,7 +735,7 @@ public abstract class ConfigurateDao extends AbstractDao {
data.getNode("groups").setValue(track.getGroups()); data.getNode("groups").setValue(track.getGroups());
saveFile(StorageLocation.TRACK, track.getName(), data); saveFile(StorageLocation.TRACK, track.getName(), data);
} catch (Exception e) { } catch (Exception e) {
return reportException(track.getName(), e); throw reportException(track.getName(), e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -732,7 +743,7 @@ public abstract class ConfigurateDao extends AbstractDao {
} }
@Override @Override
public boolean deleteTrack(Track track) { public boolean deleteTrack(Track track) throws Exception {
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
File trackFile = new File(tracksDirectory, track.getName() + fileExtension); File trackFile = new File(tracksDirectory, track.getName() + fileExtension);
@ -742,7 +753,7 @@ public abstract class ConfigurateDao extends AbstractDao {
trackFile.delete(); trackFile.delete();
} }
} catch (Exception e) { } catch (Exception e) {
return reportException(track.getName(), e); throw reportException(track.getName(), e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }

View File

@ -88,12 +88,6 @@ public class MongoDao extends AbstractDao {
this.prefix = prefix; this.prefix = prefix;
} }
private boolean reportException(Exception ex) {
plugin.getLog().warn("Exception thrown whilst performing i/o: ");
ex.printStackTrace();
return false;
}
@Override @Override
public void init() { public void init() {
MongoCredential credential = null; MongoCredential credential = null;
@ -151,116 +145,102 @@ public class MongoDao extends AbstractDao {
@Override @Override
public boolean logAction(LogEntry entry) { public boolean logAction(LogEntry entry) {
try { MongoCollection<Document> c = database.getCollection(prefix + "action");
MongoCollection<Document> c = database.getCollection(prefix + "action"); Document doc = new Document()
Document doc = new Document() .append("timestamp", entry.getTimestamp())
.append("timestamp", entry.getTimestamp()) .append("actor", entry.getActor())
.append("actor", entry.getActor()) .append("actorName", entry.getActorName())
.append("actorName", entry.getActorName()) .append("type", Character.toString(entry.getType().getCode()))
.append("type", Character.toString(entry.getType().getCode())) .append("actedName", entry.getActedName())
.append("actedName", entry.getActedName()) .append("action", entry.getAction());
.append("action", entry.getAction());
if (entry.getActed().isPresent()) { if (entry.getActed().isPresent()) {
doc.append("acted", entry.getActed().get()); doc.append("acted", entry.getActed().get());
}
c.insertOne(doc);
} catch (Exception e) {
return reportException(e);
} }
c.insertOne(doc);
return true; return true;
} }
@Override @Override
public Log getLog() { public Log getLog() {
Log.Builder log = Log.builder(); Log.Builder log = Log.builder();
try { MongoCollection<Document> c = database.getCollection(prefix + "action");
MongoCollection<Document> c = database.getCollection(prefix + "action"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { Document d = cursor.next();
Document d = cursor.next();
UUID actedUuid = null; UUID actedUuid = null;
if (d.containsKey("acted")) { if (d.containsKey("acted")) {
actedUuid = d.get("acted", UUID.class); actedUuid = d.get("acted", UUID.class);
}
ExtendedLogEntry e = ExtendedLogEntry.build()
.timestamp(d.getLong("timestamp"))
.actor(d.get("actor", UUID.class))
.actorName(d.getString("actorName"))
.type(LogEntry.Type.valueOf(d.getString("type").toCharArray()[0]))
.acted(actedUuid)
.actedName(d.getString("actedName"))
.action(d.getString("action"))
.build();
log.add(e);
} }
ExtendedLogEntry e = ExtendedLogEntry.build()
.timestamp(d.getLong("timestamp"))
.actor(d.get("actor", UUID.class))
.actorName(d.getString("actorName"))
.type(LogEntry.Type.valueOf(d.getString("type").toCharArray()[0]))
.acted(actedUuid)
.actedName(d.getString("actedName"))
.action(d.getString("action"))
.build();
log.add(e);
} }
} catch (Exception e) {
reportException(e);
return null;
} }
return log.build(); return log.build();
} }
@Override @Override
public boolean applyBulkUpdate(BulkUpdate bulkUpdate) { public boolean applyBulkUpdate(BulkUpdate bulkUpdate) {
try { if (bulkUpdate.getDataType().isIncludingUsers()) {
if (bulkUpdate.getDataType().isIncludingUsers()) { MongoCollection<Document> c = database.getCollection(prefix + "users");
MongoCollection<Document> c = database.getCollection(prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { Document d = cursor.next();
Document d = cursor.next();
UUID uuid = d.get("_id", UUID.class); UUID uuid = d.get("_id", UUID.class);
Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d)); Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d));
Set<NodeModel> results = nodes.stream() Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply) .map(bulkUpdate::apply)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
if (!nodes.equals(results)) { if (!nodes.equals(results)) {
List<Document> newNodes = results.stream() List<Document> newNodes = results.stream()
.map(MongoDao::nodeToDoc) .map(MongoDao::nodeToDoc)
.collect(Collectors.toList()); .collect(Collectors.toList());
d.append("permissions", newNodes).remove("perms"); d.append("permissions", newNodes).remove("perms");
c.replaceOne(new Document("_id", uuid), d); c.replaceOne(new Document("_id", uuid), d);
}
} }
} }
} }
}
if (bulkUpdate.getDataType().isIncludingGroups()) { if (bulkUpdate.getDataType().isIncludingGroups()) {
MongoCollection<Document> c = database.getCollection(prefix + "groups"); MongoCollection<Document> c = database.getCollection(prefix + "groups");
try (MongoCursor<Document> cursor = c.find().iterator()) { try (MongoCursor<Document> cursor = c.find().iterator()) {
while (cursor.hasNext()) { while (cursor.hasNext()) {
Document d = cursor.next(); Document d = cursor.next();
String holder = d.getString("_id"); String holder = d.getString("_id");
Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d)); Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d));
Set<NodeModel> results = nodes.stream() Set<NodeModel> results = nodes.stream()
.map(bulkUpdate::apply) .map(bulkUpdate::apply)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
if (!nodes.equals(results)) { if (!nodes.equals(results)) {
List<Document> newNodes = results.stream() List<Document> newNodes = results.stream()
.map(MongoDao::nodeToDoc) .map(MongoDao::nodeToDoc)
.collect(Collectors.toList()); .collect(Collectors.toList());
d.append("permissions", newNodes).remove("perms"); d.append("permissions", newNodes).remove("perms");
c.replaceOne(new Document("_id", holder), d); c.replaceOne(new Document("_id", holder), d);
}
} }
} }
} }
} catch (Exception e) {
reportException(e);
return false;
} }
return true; return true;
} }
@ -299,8 +279,6 @@ public class MongoDao extends AbstractDao {
} }
} }
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
user.getIoLock().unlock(); user.getIoLock().unlock();
} }
@ -318,8 +296,6 @@ public class MongoDao extends AbstractDao {
} else { } else {
return c.replaceOne(new Document("_id", user.getUuid()), userToDoc(user), new UpdateOptions().upsert(true)).wasAcknowledged(); return c.replaceOne(new Document("_id", user.getUuid()), userToDoc(user), new UpdateOptions().upsert(true)).wasAcknowledged();
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
user.getIoLock().unlock(); user.getIoLock().unlock();
} }
@ -328,17 +304,12 @@ public class MongoDao extends AbstractDao {
@Override @Override
public Set<UUID> getUniqueUsers() { public Set<UUID> getUniqueUsers() {
Set<UUID> uuids = new HashSet<>(); Set<UUID> uuids = new HashSet<>();
try { MongoCollection<Document> c = database.getCollection(prefix + "users");
MongoCollection<Document> c = database.getCollection(prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { Document d = cursor.next();
Document d = cursor.next(); uuids.add(d.get("_id", UUID.class));
uuids.add(d.get("_id", UUID.class));
}
} }
} catch (Exception e) {
reportException(e);
return null;
} }
return uuids; return uuids;
} }
@ -346,25 +317,20 @@ public class MongoDao extends AbstractDao {
@Override @Override
public List<HeldPermission<UUID>> getUsersWithPermission(String permission) { public List<HeldPermission<UUID>> getUsersWithPermission(String permission) {
ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder();
try { MongoCollection<Document> c = database.getCollection(prefix + "users");
MongoCollection<Document> c = database.getCollection(prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { Document d = cursor.next();
Document d = cursor.next(); UUID holder = d.get("_id", UUID.class);
UUID holder = d.get("_id", UUID.class);
Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d)); Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d));
for (NodeModel e : nodes) { for (NodeModel e : nodes) {
if (!e.getPermission().equalsIgnoreCase(permission)) { if (!e.getPermission().equalsIgnoreCase(permission)) {
continue; continue;
}
held.add(NodeHeldPermission.of(holder, e));
} }
held.add(NodeHeldPermission.of(holder, e));
} }
} }
} catch (Exception e) {
reportException(e);
return null;
} }
return held.build(); return held.build();
} }
@ -384,8 +350,6 @@ public class MongoDao extends AbstractDao {
c.insertOne(groupToDoc(group)); c.insertOne(groupToDoc(group));
} }
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -408,8 +372,6 @@ public class MongoDao extends AbstractDao {
Set<Node> nodes = nodesFromDoc(d).stream().map(NodeModel::toNode).collect(Collectors.toSet()); Set<Node> nodes = nodesFromDoc(d).stream().map(NodeModel::toNode).collect(Collectors.toSet());
group.setEnduringNodes(nodes); group.setEnduringNodes(nodes);
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -420,25 +382,33 @@ public class MongoDao extends AbstractDao {
@Override @Override
public boolean loadAllGroups() { public boolean loadAllGroups() {
List<String> groups = new ArrayList<>(); List<String> groups = new ArrayList<>();
try { MongoCollection<Document> c = database.getCollection(prefix + "groups");
MongoCollection<Document> c = database.getCollection(prefix + "groups"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { String name = cursor.next().getString("_id");
String name = cursor.next().getString("_id"); groups.add(name);
groups.add(name);
}
} }
} catch (Exception e) {
reportException(e);
return false;
} }
groups.forEach(this::loadGroup); boolean success = true;
for (String g : groups) {
try {
loadGroup(g);
} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (!success) {
throw new RuntimeException("Exception occurred whilst loading a group");
}
GroupManager gm = plugin.getGroupManager(); GroupManager gm = plugin.getGroupManager();
gm.getAll().values().stream() gm.getAll().values().stream()
.filter(g -> !groups.contains(g.getName())) .filter(g -> !groups.contains(g.getName()))
.forEach(gm::unload); .forEach(gm::unload);
return true; return true;
} }
@ -448,8 +418,6 @@ public class MongoDao extends AbstractDao {
try { try {
MongoCollection<Document> c = database.getCollection(prefix + "groups"); MongoCollection<Document> c = database.getCollection(prefix + "groups");
return c.replaceOne(new Document("_id", group.getName()), groupToDoc(group), new UpdateOptions().upsert(true)).wasAcknowledged(); return c.replaceOne(new Document("_id", group.getName()), groupToDoc(group), new UpdateOptions().upsert(true)).wasAcknowledged();
} catch (Exception e) {
return reportException(e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -461,8 +429,6 @@ public class MongoDao extends AbstractDao {
try { try {
MongoCollection<Document> c = database.getCollection(prefix + "groups"); MongoCollection<Document> c = database.getCollection(prefix + "groups");
return c.deleteOne(new Document("_id", group.getName())).wasAcknowledged(); return c.deleteOne(new Document("_id", group.getName())).wasAcknowledged();
} catch (Exception e) {
return reportException(e);
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
@ -471,25 +437,20 @@ public class MongoDao extends AbstractDao {
@Override @Override
public List<HeldPermission<String>> getGroupsWithPermission(String permission) { public List<HeldPermission<String>> getGroupsWithPermission(String permission) {
ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder();
try { MongoCollection<Document> c = database.getCollection(prefix + "groups");
MongoCollection<Document> c = database.getCollection(prefix + "groups"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { Document d = cursor.next();
Document d = cursor.next();
String holder = d.getString("_id"); String holder = d.getString("_id");
Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d)); Set<NodeModel> nodes = new HashSet<>(nodesFromDoc(d));
for (NodeModel e : nodes) { for (NodeModel e : nodes) {
if (!e.getPermission().equalsIgnoreCase(permission)) { if (!e.getPermission().equalsIgnoreCase(permission)) {
continue; continue;
}
held.add(NodeHeldPermission.of(holder, e));
} }
held.add(NodeHeldPermission.of(holder, e));
} }
} }
} catch (Exception e) {
reportException(e);
return null;
} }
return held.build(); return held.build();
} }
@ -509,8 +470,6 @@ public class MongoDao extends AbstractDao {
track.setGroups((List<String>) d.get("groups")); track.setGroups((List<String>) d.get("groups"));
} }
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -532,8 +491,6 @@ public class MongoDao extends AbstractDao {
} }
return false; return false;
} }
} catch (Exception e) {
return reportException(e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -542,25 +499,33 @@ public class MongoDao extends AbstractDao {
@Override @Override
public boolean loadAllTracks() { public boolean loadAllTracks() {
List<String> tracks = new ArrayList<>(); List<String> tracks = new ArrayList<>();
try { MongoCollection<Document> c = database.getCollection(prefix + "tracks");
MongoCollection<Document> c = database.getCollection(prefix + "tracks"); try (MongoCursor<Document> cursor = c.find().iterator()) {
try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) {
while (cursor.hasNext()) { String name = cursor.next().getString("_id");
String name = cursor.next().getString("_id"); tracks.add(name);
tracks.add(name);
}
} }
} catch (Exception e) {
reportException(e);
return false;
} }
tracks.forEach(this::loadTrack); boolean success = true;
for (String t : tracks) {
try {
loadTrack(t);
} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (!success) {
throw new RuntimeException("Exception occurred whilst loading a track");
}
TrackManager tm = plugin.getTrackManager(); TrackManager tm = plugin.getTrackManager();
tm.getAll().values().stream() tm.getAll().values().stream()
.filter(t -> !tracks.contains(t.getName())) .filter(t -> !tracks.contains(t.getName()))
.forEach(tm::unload); .forEach(tm::unload);
return true; return true;
} }
@ -570,8 +535,6 @@ public class MongoDao extends AbstractDao {
try { try {
MongoCollection<Document> c = database.getCollection(prefix + "tracks"); MongoCollection<Document> c = database.getCollection(prefix + "tracks");
return c.replaceOne(new Document("_id", track.getName()), trackToDoc(track)).wasAcknowledged(); return c.replaceOne(new Document("_id", track.getName()), trackToDoc(track)).wasAcknowledged();
} catch (Exception e) {
return reportException(e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -583,8 +546,6 @@ public class MongoDao extends AbstractDao {
try { try {
MongoCollection<Document> c = database.getCollection(prefix + "tracks"); MongoCollection<Document> c = database.getCollection(prefix + "tracks");
return c.deleteOne(new Document("_id", track.getName())).wasAcknowledged(); return c.deleteOne(new Document("_id", track.getName())).wasAcknowledged();
} catch (Exception e) {
return reportException(e);
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
} }
@ -592,45 +553,31 @@ public class MongoDao extends AbstractDao {
@Override @Override
public boolean saveUUIDData(UUID uuid, String username) { public boolean saveUUIDData(UUID uuid, String username) {
try { MongoCollection<Document> c = database.getCollection(prefix + "uuid");
MongoCollection<Document> c = database.getCollection(prefix + "uuid"); c.replaceOne(new Document("_id", uuid), new Document("_id", uuid).append("name", username.toLowerCase()), new UpdateOptions().upsert(true));
c.replaceOne(new Document("_id", uuid), new Document("_id", uuid).append("name", username.toLowerCase()), new UpdateOptions().upsert(true));
} catch (Exception e) {
return reportException(e);
}
return true; return true;
} }
@Override @Override
public UUID getUUID(String username) { public UUID getUUID(String username) {
try { MongoCollection<Document> c = database.getCollection(prefix + "uuid");
MongoCollection<Document> c = database.getCollection(prefix + "uuid"); try (MongoCursor<Document> cursor = c.find(new Document("name", username.toLowerCase())).iterator()) {
try (MongoCursor<Document> cursor = c.find(new Document("name", username.toLowerCase())).iterator()) { if (cursor.hasNext()) {
if (cursor.hasNext()) { return cursor.next().get("_id", UUID.class);
return cursor.next().get("_id", UUID.class);
}
} }
return null;
} catch (Exception e) {
reportException(e);
return null;
} }
return null;
} }
@Override @Override
public String getName(UUID uuid) { public String getName(UUID uuid) {
try { MongoCollection<Document> c = database.getCollection(prefix + "uuid");
MongoCollection<Document> c = database.getCollection(prefix + "uuid"); try (MongoCursor<Document> cursor = c.find(new Document("_id", uuid)).iterator()) {
try (MongoCursor<Document> cursor = c.find(new Document("_id", uuid)).iterator()) { if (cursor.hasNext()) {
if (cursor.hasNext()) { return cursor.next().get("name", String.class);
return cursor.next().get("name", String.class);
}
} }
return null;
} catch (Exception e) {
reportException(e);
return null;
} }
return null;
} }
private static Document userToDoc(User user) { private static Document userToDoc(User user) {

View File

@ -210,7 +210,6 @@ public class SqlDao extends AbstractDao {
} catch (Exception e) { } catch (Exception e) {
plugin.getLog().severe("Error occurred whilst initialising the database."); plugin.getLog().severe("Error occurred whilst initialising the database.");
e.printStackTrace(); e.printStackTrace();
shutdown();
} }
} }
@ -229,7 +228,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean logAction(LogEntry entry) { public boolean logAction(LogEntry entry) throws SQLException {
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(ACTION_INSERT))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(ACTION_INSERT))) {
ps.setLong(1, entry.getTimestamp()); ps.setLong(1, entry.getTimestamp());
@ -240,16 +239,13 @@ public class SqlDao extends AbstractDao {
ps.setString(6, entry.getActedName()); ps.setString(6, entry.getActedName());
ps.setString(7, entry.getAction()); ps.setString(7, entry.getAction());
ps.execute(); ps.execute();
return true;
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true;
} }
@Override @Override
public Log getLog() { public Log getLog() throws SQLException {
final Log.Builder log = Log.builder(); final Log.Builder log = Log.builder();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(ACTION_SELECT_ALL))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(ACTION_SELECT_ALL))) {
@ -270,51 +266,35 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return log.build(); return log.build();
} }
@Override @Override
public boolean applyBulkUpdate(BulkUpdate bulkUpdate) { public boolean applyBulkUpdate(BulkUpdate bulkUpdate) throws SQLException {
boolean success = true;
String queryString = bulkUpdate.buildAsSql(); String queryString = bulkUpdate.buildAsSql();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
if (bulkUpdate.getDataType().isIncludingUsers()) { if (bulkUpdate.getDataType().isIncludingUsers()) {
String table = prefix.apply("{prefix}user_permissions"); String table = prefix.apply("{prefix}user_permissions");
try (Statement s = c.createStatement()) { try (Statement s = c.createStatement()) {
s.execute(queryString.replace("{table}", table)); s.execute(queryString.replace("{table}", table));
} catch (SQLException e) {
e.printStackTrace();
success = false;
} }
} }
if (bulkUpdate.getDataType().isIncludingGroups()) { if (bulkUpdate.getDataType().isIncludingGroups()) {
String table = prefix.apply("{prefix}group_permissions"); String table = prefix.apply("{prefix}group_permissions");
try (Statement s = c.createStatement()) { try (Statement s = c.createStatement()) {
s.execute(queryString.replace("{table}", table)); s.execute(queryString.replace("{table}", table));
} catch (SQLException e) {
e.printStackTrace();
success = false;
} }
} }
} catch (SQLException e) {
e.printStackTrace();
success = false;
} }
return true;
return success;
} }
@Override @Override
public boolean loadUser(UUID uuid, String username) { public boolean loadUser(UUID uuid, String username) throws SQLException {
User user = plugin.getUserManager().getOrMake(UserIdentifier.of(uuid, username)); User user = plugin.getUserManager().getOrMake(UserIdentifier.of(uuid, username));
user.getIoLock().lock(); user.getIoLock().lock();
try { try {
@ -339,9 +319,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
// Collect user meta (username & primary group) // Collect user meta (username & primary group)
@ -356,9 +333,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
// update username & primary group // update username & primary group
@ -398,7 +372,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean saveUser(User user) { public boolean saveUser(User user) throws SQLException {
user.getIoLock().lock(); user.getIoLock().lock();
try { try {
// Empty data - just delete from the DB. // Empty data - just delete from the DB.
@ -413,9 +387,6 @@ public class SqlDao extends AbstractDao {
ps.setString(2, user.getUuid().toString()); ps.setString(2, user.getUuid().toString());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} }
@ -438,8 +409,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
return false;
} }
Set<NodeModel> local = user.getEnduringNodes().values().stream().map(NodeModel::fromNode).collect(Collectors.toSet()); Set<NodeModel> local = user.getEnduringNodes().values().stream().map(NodeModel::fromNode).collect(Collectors.toSet());
@ -464,9 +433,6 @@ public class SqlDao extends AbstractDao {
} }
ps.executeBatch(); ps.executeBatch();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
} }
@ -485,9 +451,6 @@ public class SqlDao extends AbstractDao {
} }
ps.executeBatch(); ps.executeBatch();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
} }
@ -518,9 +481,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
@ -530,7 +490,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public Set<UUID> getUniqueUsers() { public Set<UUID> getUniqueUsers() throws SQLException {
Set<UUID> uuids = new HashSet<>(); Set<UUID> uuids = new HashSet<>();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(USER_PERMISSIONS_SELECT_DISTINCT))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(USER_PERMISSIONS_SELECT_DISTINCT))) {
@ -541,15 +501,12 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return uuids; return uuids;
} }
@Override @Override
public List<HeldPermission<UUID>> getUsersWithPermission(String permission) { public List<HeldPermission<UUID>> getUsersWithPermission(String permission) throws SQLException {
ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<UUID>> held = ImmutableList.builder();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(USER_PERMISSIONS_SELECT_PERMISSION))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(USER_PERMISSIONS_SELECT_PERMISSION))) {
@ -568,15 +525,12 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return held.build(); return held.build();
} }
@Override @Override
public boolean createAndLoadGroup(String name) { public boolean createAndLoadGroup(String name) throws SQLException {
String query; String query;
switch (provider.getName()) { switch (provider.getName()) {
case "H2": case "H2":
@ -598,16 +552,13 @@ public class SqlDao extends AbstractDao {
ps.setString(1, name); ps.setString(1, name);
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return loadGroup(name); return loadGroup(name);
} }
@Override @Override
public boolean loadGroup(String name) { public boolean loadGroup(String name) throws SQLException {
// Check the group actually exists // Check the group actually exists
List<String> groups = new ArrayList<>(); List<String> groups = new ArrayList<>();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
@ -619,9 +570,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
if (!groups.contains(name)) { if (!groups.contains(name)) {
@ -649,9 +597,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
if (!data.isEmpty()) { if (!data.isEmpty()) {
@ -668,7 +613,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean loadAllGroups() { public boolean loadAllGroups() throws SQLException {
List<String> groups = new ArrayList<>(); List<String> groups = new ArrayList<>();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(GROUP_SELECT_ALL))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(GROUP_SELECT_ALL))) {
@ -678,30 +623,32 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
boolean success = true; boolean success = true;
for (String g : groups) { for (String g : groups) {
if (!loadGroup(g)) { try {
loadGroup(g);
} catch (Exception e) {
e.printStackTrace();
success = false; success = false;
} }
} }
if (success) { if (!success) {
GroupManager gm = plugin.getGroupManager(); throw new RuntimeException("Exception occurred whilst loading a group");
gm.getAll().values().stream()
.filter(g -> !groups.contains(g.getName()))
.forEach(gm::unload);
} }
return success;
GroupManager gm = plugin.getGroupManager();
gm.getAll().values().stream()
.filter(g -> !groups.contains(g.getName()))
.forEach(gm::unload);
return true;
} }
@Override @Override
public boolean saveGroup(Group group) { public boolean saveGroup(Group group) throws SQLException {
group.getIoLock().lock(); group.getIoLock().lock();
try { try {
// Empty data, just delete. // Empty data, just delete.
@ -711,9 +658,6 @@ public class SqlDao extends AbstractDao {
ps.setString(1, group.getName()); ps.setString(1, group.getName());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} }
@ -736,9 +680,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
Set<NodeModel> local = group.getEnduringNodes().values().stream().map(NodeModel::fromNode).collect(Collectors.toSet()); Set<NodeModel> local = group.getEnduringNodes().values().stream().map(NodeModel::fromNode).collect(Collectors.toSet());
@ -763,9 +704,6 @@ public class SqlDao extends AbstractDao {
} }
ps.executeBatch(); ps.executeBatch();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
} }
@ -784,9 +722,6 @@ public class SqlDao extends AbstractDao {
} }
ps.executeBatch(); ps.executeBatch();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
} }
@ -797,7 +732,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean deleteGroup(Group group) { public boolean deleteGroup(Group group) throws SQLException {
group.getIoLock().lock(); group.getIoLock().lock();
try { try {
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
@ -810,20 +745,15 @@ public class SqlDao extends AbstractDao {
ps.setString(1, group.getName()); ps.setString(1, group.getName());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} finally { } finally {
group.getIoLock().unlock(); group.getIoLock().unlock();
} }
} }
@Override @Override
public List<HeldPermission<String>> getGroupsWithPermission(String permission) { public List<HeldPermission<String>> getGroupsWithPermission(String permission) throws SQLException {
ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder(); ImmutableList.Builder<HeldPermission<String>> held = ImmutableList.builder();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(GROUP_PERMISSIONS_SELECT_PERMISSION))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(GROUP_PERMISSIONS_SELECT_PERMISSION))) {
@ -842,15 +772,12 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return held.build(); return held.build();
} }
@Override @Override
public boolean createAndLoadTrack(String name) { public boolean createAndLoadTrack(String name) throws SQLException {
Track track = plugin.getTrackManager().getOrMake(name); Track track = plugin.getTrackManager().getOrMake(name);
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
@ -867,9 +794,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
if (exists.get()) { if (exists.get()) {
@ -884,9 +808,6 @@ public class SqlDao extends AbstractDao {
ps.setString(2, json); ps.setString(2, json);
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} }
@ -897,7 +818,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean loadTrack(String name) { public boolean loadTrack(String name) throws SQLException {
Track track = plugin.getTrackManager().getOrMake(name); Track track = plugin.getTrackManager().getOrMake(name);
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
@ -913,9 +834,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
track.setGroups(gson.fromJson(groups.get(), LIST_STRING_TYPE)); track.setGroups(gson.fromJson(groups.get(), LIST_STRING_TYPE));
@ -927,7 +845,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean loadAllTracks() { public boolean loadAllTracks() throws SQLException {
List<String> tracks = new ArrayList<>(); List<String> tracks = new ArrayList<>();
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(prefix.apply(TRACK_SELECT_ALL))) { try (PreparedStatement ps = c.prepareStatement(prefix.apply(TRACK_SELECT_ALL))) {
@ -937,29 +855,32 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
boolean success = true; boolean success = true;
for (String t : tracks) { for (String t : tracks) {
if (!loadTrack(t)) { try {
loadTrack(t);
} catch (Exception e) {
e.printStackTrace();
success = false; success = false;
} }
} }
if (success) { if (!success) {
TrackManager tm = plugin.getTrackManager(); throw new RuntimeException("Exception occurred whilst loading a track");
tm.getAll().values().stream()
.filter(t -> !tracks.contains(t.getName()))
.forEach(tm::unload);
} }
return success;
TrackManager tm = plugin.getTrackManager();
tm.getAll().values().stream()
.filter(t -> !tracks.contains(t.getName()))
.forEach(tm::unload);
return true;
} }
@Override @Override
public boolean saveTrack(Track track) { public boolean saveTrack(Track track) throws SQLException {
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
String s = gson.toJson(track.getGroups()); String s = gson.toJson(track.getGroups());
@ -969,9 +890,6 @@ public class SqlDao extends AbstractDao {
ps.setString(2, track.getName()); ps.setString(2, track.getName());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} finally { } finally {
@ -980,7 +898,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean deleteTrack(Track track) { public boolean deleteTrack(Track track) throws SQLException {
track.getIoLock().lock(); track.getIoLock().lock();
try { try {
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
@ -988,9 +906,6 @@ public class SqlDao extends AbstractDao {
ps.setString(1, track.getName()); ps.setString(1, track.getName());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
} finally { } finally {
track.getIoLock().unlock(); track.getIoLock().unlock();
@ -1001,7 +916,7 @@ public class SqlDao extends AbstractDao {
} }
@Override @Override
public boolean saveUUIDData(UUID uuid, String username) { public boolean saveUUIDData(UUID uuid, String username) throws SQLException {
final String u = username.toLowerCase(); final String u = username.toLowerCase();
AtomicReference<String> remoteUserName = new AtomicReference<>(null); AtomicReference<String> remoteUserName = new AtomicReference<>(null);
@ -1012,8 +927,6 @@ public class SqlDao extends AbstractDao {
ps.setString(2, uuid.toString()); ps.setString(2, uuid.toString());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
} }
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
@ -1025,9 +938,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
if (remoteUserName.get() != null) { if (remoteUserName.get() != null) {
@ -1042,9 +952,6 @@ public class SqlDao extends AbstractDao {
ps.setString(2, uuid.toString()); ps.setString(2, uuid.toString());
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} else { } else {
@ -1056,16 +963,13 @@ public class SqlDao extends AbstractDao {
ps.setString(3, "default"); ps.setString(3, "default");
ps.execute(); ps.execute();
} }
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
return true; return true;
} }
} }
@Override @Override
public UUID getUUID(String username) { public UUID getUUID(String username) throws SQLException {
final String u = username.toLowerCase(); final String u = username.toLowerCase();
final AtomicReference<UUID> uuid = new AtomicReference<>(null); final AtomicReference<UUID> uuid = new AtomicReference<>(null);
@ -1078,16 +982,13 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return uuid.get(); return uuid.get();
} }
@Override @Override
public String getName(UUID uuid) { public String getName(UUID uuid) throws SQLException {
final AtomicReference<String> name = new AtomicReference<>(null); final AtomicReference<String> name = new AtomicReference<>(null);
try (Connection c = provider.getConnection()) { try (Connection c = provider.getConnection()) {
@ -1099,9 +1000,6 @@ public class SqlDao extends AbstractDao {
} }
} }
} }
} catch (SQLException e) {
e.printStackTrace();
return null;
} }
return name.get(); return name.get();

View File

@ -41,7 +41,7 @@ import java.util.concurrent.CompletableFuture;
@UtilityClass @UtilityClass
public class LoginHelper { public class LoginHelper {
public static User loadUser(LuckPermsPlugin plugin, UUID u, String username, boolean joinUuidSave) { public static User loadUser(LuckPermsPlugin plugin, UUID u, String username, boolean joinUuidSave) throws Exception {
final long startTime = System.currentTimeMillis(); final long startTime = System.currentTimeMillis();
final UuidCache cache = plugin.getUuidCache(); final UuidCache cache = plugin.getUuidCache();

View File

@ -273,7 +273,7 @@ data {
# This setting controls the maximum number of milliseconds that the plugin will wait for a # This setting controls the maximum number of milliseconds that the plugin will wait for a
# connection from the pool, before timing out. # connection from the pool, before timing out.
connection-timeout=15000 # 15 seconds connection-timeout=5000 # 5 seconds
# This setting allows you to define extra properties for connections. # This setting allows you to define extra properties for connections.
properties { properties {