Fixed old code smells:

Bug:
- Unused result of orElseThrow in DataStoreQueries
- Missing synchronized keywords in ConfigChange
- PlanConfig#hashCode since equals exists

Blocker:
- Add assertion to BungeeSystemTest, SessionTest, CommonDBTest,
  LocaleSystemTest, FileWatcherTest
- Removed BungeeBukkitConnectionTest (Not executed)

Critical:
- Fix typo in ErrorPageLang.AUTHENTICATION_FAILED_401 name
- Duplicate Exception definition in ConfigValueParser

Major:
- Renamed 'name' to 'playerName' in BukkitImporter
- Non generic exceptions to Reflection
- Extracted tenary to if in TableContainer, ProviderInformation

And some minor smells
This commit is contained in:
Rsl1122 2019-05-03 15:11:56 +03:00
parent 83343471a6
commit 7510841ebd
32 changed files with 115 additions and 151 deletions

View File

@ -175,11 +175,11 @@ public abstract class BukkitImporter implements Importer {
}
private BaseUser toBaseUser(UserImportData userImportData) {
UUID uuid = userImportData.getUuid();
String name = userImportData.getName();
UUID playerUUID = userImportData.getUuid();
String playerName = userImportData.getName();
long registered = userImportData.getRegistered();
int timesKicked = userImportData.getTimesKicked();
return new BaseUser(uuid, name, registered, timesKicked);
return new BaseUser(playerUUID, playerName, registered, timesKicked);
}
private UserInfo toUserInfo(UserImportData userImportData) {

View File

@ -122,7 +122,7 @@ public final class Reflection {
try {
return (T) field.get(target);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot access reflection.", e);
throw new IllegalStateException("Cannot access reflection.", e);
}
}
@ -131,7 +131,7 @@ public final class Reflection {
try {
field.set(target, value);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot access reflection.", e);
throw new IllegalStateException("Cannot access reflection.", e);
}
}
@ -197,7 +197,7 @@ public final class Reflection {
try {
return method.invoke(target, arguments);
} catch (Exception e) {
throw new RuntimeException("Cannot invoke method " + method, e);
throw new IllegalStateException("Cannot invoke method " + method, e);
}
};
}
@ -240,7 +240,7 @@ public final class Reflection {
try {
return constructor.newInstance(arguments);
} catch (Exception e) {
throw new RuntimeException("Cannot invoke constructor " + constructor, e);
throw new IllegalStateException("Cannot invoke constructor " + constructor, e);
}
};
}

View File

@ -69,6 +69,7 @@ public class BungeeSystemTest {
dbSystem.setActiveDatabase(db);
bungeeSystem.enable();
assertTrue(bungeeSystem.isEnabled());
} finally {
bungeeSystem.disable();
}
@ -90,8 +91,7 @@ public class BungeeSystemTest {
db.setTransactionExecutorServiceProvider(MoreExecutors::newDirectExecutorService);
dbSystem.setActiveDatabase(db);
bungeeSystem.enable();
assertTrue(bungeeSystem.isEnabled());
bungeeSystem.enable(); // Throws EnableException
} finally {
bungeeSystem.disable();
}
@ -107,7 +107,7 @@ public class BungeeSystemTest {
config.set(WebserverSettings.PORT, TEST_PORT_NUMBER);
config.set(ProxySettings.IP, "8.8.8.8");
bungeeSystem.enable();
bungeeSystem.enable(); // Throws EnableException
} finally {
bungeeSystem.disable();
}

View File

@ -60,7 +60,7 @@ public class ManageDisableCommand extends CommandNode {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
if ("kickcount".equals(args[0].toLowerCase())) {
if ("kickcount".equalsIgnoreCase(args[0])) {
status.setCountKicks(false);
sender.sendMessage(locale.getString(CommandLang.FEATURE_DISABLED, "Kick Counting"));
} else {

View File

@ -92,10 +92,7 @@ public class TableContainer {
if (i > maxIndex) {
body.append("<td>-");
} else {
Serializable value = row[i];
Formatter formatter = formatters[i];
body.append("<td").append(formatter != null ? " data-order=\"" + value + "\">" : ">");
body.append(formatter != null ? formatter.apply(value) : (value != null ? value : '-'));
appendValue(body, row[i], formatters[i]);
}
body.append("</td>");
} catch (ClassCastException | ArrayIndexOutOfBoundsException e) {
@ -105,6 +102,15 @@ public class TableContainer {
body.append("</tr>");
}
private void appendValue(StringBuilder body, Serializable value, Formatter formatter) {
body.append("<td").append(formatter != null ? " data-order=\"" + value + "\">" : ">");
if (formatter != null) {
body.append(formatter.apply(value));
} else {
body.append(value != null ? value : '-');
}
}
public final void setColor(String color) {
this.color = color;
}

View File

@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit;
public abstract class AbstractHealthInfo {
protected final String subNote = "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
protected static final String SUB_NOTE = "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
protected final List<String> notes;
protected final long now;
@ -109,7 +109,7 @@ public abstract class AbstractHealthInfo {
StringBuilder remainNote = new StringBuilder();
if (activeFWAGNum != 0) {
remainNote.append(subNote);
remainNote.append(SUB_NOTE);
if (percRemain > 0.5) {
remainNote.append(Icons.GREEN_THUMB);
} else if (percRemain > 0.2) {

View File

@ -124,7 +124,7 @@ public class HealthInformation extends AbstractHealthInfo {
double aboveThreshold = tpsMutator.percentageTPSAboveThreshold(lowTPSThreshold);
long tpsSpikeMonth = analysisContainer.getValue(AnalysisKeys.TPS_SPIKE_MONTH).orElse(0);
StringBuilder avgLowThresholdString = new StringBuilder(subNote);
StringBuilder avgLowThresholdString = new StringBuilder(SUB_NOTE);
if (aboveThreshold >= 0.96) {
avgLowThresholdString.append(Icons.GREEN_THUMB);
} else if (aboveThreshold >= 0.9) {

View File

@ -112,7 +112,7 @@ public class NetworkHealthInformation extends AbstractHealthInfo {
.map(c -> {
int playersPerMonth = c.getUnsafe(AnalysisKeys.AVG_PLAYERS_MONTH);
Server server = c.getUnsafe(serverKey);
return subNote + (playersPerMonth >= average && playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
return SUB_NOTE + (playersPerMonth >= average && playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
server.getName() + ": " + playersPerMonth;
}).forEach(subNotes::append);
addNote(icon + " " + decimalFormatter.apply(average) + uniquePlayersNote + subNotes.toString());
@ -139,7 +139,7 @@ public class NetworkHealthInformation extends AbstractHealthInfo {
.map(c -> {
int playersPerMonth = c.getUnsafe(AnalysisKeys.AVG_PLAYERS_NEW_MONTH);
Server server = c.getUnsafe(serverKey);
return subNote + (playersPerMonth >= average && playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
return SUB_NOTE + (playersPerMonth >= average && playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
server.getName() + ": " + playersPerMonth;
}).forEach(subNotes::append);
addNote(icon + " " + decimalFormatter.apply(average) + newPlayersNote + subNotes.toString());
@ -179,7 +179,7 @@ public class NetworkHealthInformation extends AbstractHealthInfo {
.map(c -> {
int playersPerMonth = c.getUnsafe(AnalysisKeys.PLAYERS_MONTH);
Server server = c.getUnsafe(serverKey);
return subNote + (playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
return SUB_NOTE + (playersPerMonth > 0 ? Icons.GREEN_PLUS : Icons.RED_MINUS) + " " +
server.getName() + ": " + playersPerMonth;
}).forEach(subNotes::append);
addNote(icon.toHtml() + " " + uniquePlayersNote + subNotes.toString());

View File

@ -27,6 +27,7 @@ import com.djrapitops.plan.db.access.ExecBatchStatement;
import com.djrapitops.plan.db.access.ExecStatement;
import com.djrapitops.plan.db.access.Executable;
import com.djrapitops.plan.db.sql.tables.*;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@ -88,7 +89,7 @@ public class DataStoreQueries {
* @throws IllegalArgumentException If {@link Session#endSession(long)} has not yet been called.
*/
public static Executable storeSession(Session session) {
session.getValue(SessionKeys.END).orElseThrow(() -> new IllegalArgumentException("Attempted to save a session that has not ended."));
Verify.isTrue(session.supports(SessionKeys.END), () -> new IllegalArgumentException("Attempted to save a session that has not ended."));
return connection -> {
storeSessionInformation(session).execute(connection);
storeSessionKills(session).execute(connection);

View File

@ -157,4 +157,8 @@ public abstract class Transaction {
public String toString() {
return getClass().getSimpleName() + (success ? " (finished)" : "");
}
public boolean wasSuccessful() {
return success;
}
}

View File

@ -47,7 +47,7 @@ public class CallerImplementation implements Caller {
}
@Override
public void updatePlayerData(UUID playerUUID, String playerName) throws IllegalArgumentException {
public void updatePlayerData(UUID playerUUID, String playerName) {
Verify.nullCheck(playerUUID, () -> new IllegalArgumentException("'playerUUID' can not be null!"));
Verify.nullCheck(playerName, () -> new IllegalArgumentException("'playerName' can not be null!"));
processing.submitNonCritical(() -> extensionServiceImplementation.updatePlayerValues(gatherer, playerUUID, playerName, CallEvents.MANUAL));

View File

@ -21,6 +21,7 @@ import com.djrapitops.plan.extension.icon.Icon;
import com.djrapitops.plan.extension.implementation.results.ExtensionDescriptive;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
import java.util.Optional;
/**
@ -48,10 +49,38 @@ public class ProviderInformation extends ExtensionDescriptive {
}
public Optional<String> getTab() {
return tab == null || tab.isEmpty() ? Optional.empty() : Optional.of(StringUtils.truncate(tab, 50));
return tab == null || tab.isEmpty()
? Optional.empty()
: Optional.of(StringUtils.truncate(tab, 50));
}
public Optional<String> getCondition() {
return condition == null || condition.value().isEmpty() ? Optional.empty() : Optional.of((condition.negated() ? "not_" : "") + StringUtils.truncate(condition.value(), 50));
if (condition == null || condition.value().isEmpty()) {
return Optional.empty();
} else if (condition.negated()) {
return Optional.of("not_" + getTruncatedConditionName());
} else {
return Optional.of(getTruncatedConditionName());
}
}
private String getTruncatedConditionName() {
return StringUtils.truncate(condition.value(), 50);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ProviderInformation)) return false;
if (!super.equals(o)) return false;
ProviderInformation that = (ProviderInformation) o;
return pluginName.equals(that.pluginName) &&
Objects.equals(tab, that.tab) &&
Objects.equals(condition, that.condition);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), pluginName, tab, condition);
}
}

View File

@ -27,7 +27,7 @@ public enum ErrorPageLang implements Lang {
NOT_PLAYED_404("Player has not played on this server."),
UNKNOWN_PAGE_404("Make sure you're accessing a link given by a command, Examples:</p><p>/player/PlayerName<br>/server/ServerName</p>"),
UNAUTHORIZED_401("Unauthorized"),
AUTHENTICATION_FAIlED_401("Authentication Failed."),
AUTHENTICATION_FAILED_401("Authentication Failed."),
AUTH_FAIL_TIPS_401("- Ensure you have registered a user with <b>/plan register</b><br>- Check that the username and password are correct<br>- Username and password are case-sensitive<br><br>If you have forgotten your password, ask a staff member to delete your old user and re-register."),
FORBIDDEN_403("Forbidden"),
ACCESS_DENIED_403("Access Denied"),

View File

@ -41,7 +41,7 @@ public interface ConfigChange {
}
@Override
public void apply(Config config) {
public synchronized void apply(Config config) {
if (!config.moveChild(oldPath, newPath)) {
throw new IllegalStateException("Failed to move config node from '" + oldPath + "' to '" + newPath + "'");
}
@ -63,7 +63,7 @@ public interface ConfigChange {
}
@Override
public void apply(Config config) {
public synchronized void apply(Config config) {
config.getNode(oldPath).ifPresent(oldNode -> config.addNode(newPath).copyAll(oldNode));
}

View File

@ -76,6 +76,10 @@ public interface ConfigValueParser<T> {
*/
String decompose(T ofValue);
static IllegalArgumentException nullInvalidException() {
return new IllegalArgumentException("Null value is not valid for saving");
}
class StringParser implements ConfigValueParser<String> {
@Override
public String compose(String fromValue) {
@ -89,7 +93,7 @@ public interface ConfigValueParser<T> {
@Override
public String decompose(String value) {
Verify.nullCheck(value, () -> new IllegalArgumentException("Null value is not valid for saving"));
Verify.nullCheck(value, ConfigValueParser::nullInvalidException);
boolean surroundedByQuotes = value.startsWith("'") || value.endsWith("'");
boolean surroundedByDoubleQuotes = value.startsWith("\"") || value.endsWith("\"");
@ -116,7 +120,7 @@ public interface ConfigValueParser<T> {
@Override
public String decompose(Integer ofValue) {
Verify.nullCheck(ofValue, () -> new IllegalArgumentException("Null value is not valid for saving"));
Verify.nullCheck(ofValue, ConfigValueParser::nullInvalidException);
return Integer.toString(ofValue);
}
}
@ -133,7 +137,7 @@ public interface ConfigValueParser<T> {
@Override
public String decompose(Long ofValue) {
Verify.nullCheck(ofValue, () -> new IllegalArgumentException("Null value is not valid for saving"));
Verify.nullCheck(ofValue, ConfigValueParser::nullInvalidException);
return Long.toString(ofValue);
}
}
@ -146,7 +150,7 @@ public interface ConfigValueParser<T> {
@Override
public String decompose(Boolean ofValue) {
Verify.nullCheck(ofValue, () -> new IllegalArgumentException("Null value is not valid for saving"));
Verify.nullCheck(ofValue, ConfigValueParser::nullInvalidException);
return Boolean.toString(ofValue);
}
}
@ -174,7 +178,7 @@ public interface ConfigValueParser<T> {
@Override
public String decompose(List<String> ofValue) {
Verify.nullCheck(ofValue, () -> new IllegalArgumentException("Null value is not valid for saving"));
Verify.nullCheck(ofValue, ConfigValueParser::nullInvalidException);
StringBuilder decomposedString = new StringBuilder();
for (String value : ofValue) {

View File

@ -27,6 +27,7 @@ import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
@ -134,4 +135,9 @@ public class PlanConfig extends Config {
if (o == null) return false;
return super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode());
}
}

View File

@ -59,7 +59,7 @@ public class RawDataResponse extends JSONResponse<Map<String, Object>> {
private static List handleList(List list) {
if (list.stream().findAny().orElse(null) instanceof DataContainer) {
return (List) list.stream().map((obj) -> mapToNormalMap((DataContainer) obj)).collect(Collectors.toList());
return (List) list.stream().map(obj -> mapToNormalMap((DataContainer) obj)).collect(Collectors.toList());
}
return list;
}

View File

@ -75,7 +75,7 @@ class PlayerSessionTable extends TableContainer {
String world = worldAliasSettings.getLongestWorldPlayed(session);
String toolTip = "Session ID: " + session.getValue(SessionKeys.DB_ID)
.map(id -> Integer.toString(id))
.map(Object::toString)
.orElse("Not Saved.");
addRow(Html.LINK_TOOLTIP.parse(inspectUrl, playerName, toolTip), start, length, world);

View File

@ -76,7 +76,7 @@ class ServerSessionTable extends TableContainer {
String world = worldAliasSettings.getLongestWorldPlayed(session);
String toolTip = "Session ID: " + session.getValue(SessionKeys.DB_ID)
.map(id -> Integer.toString(id))
.map(Object::toString)
.orElse("Not Saved.");
String playerName = playerNames.getOrDefault(session.getValue(SessionKeys.UUID).orElse(null), "Unknown");

View File

@ -246,7 +246,7 @@ HTML ERRORS - ACCESS_DENIED_403 || 拒绝访问
HTML ERRORS - ANALYSIS_REFRESH || 正在刷新分析···
HTML ERRORS - ANALYSIS_REFRESH_LONG || 正在执行分析,请在几秒后刷新页面···
HTML ERRORS - AUTH_FAIL_TIPS_401 || - 确保您已使用 <b>/plan register</b> 注册用户<br>- 检查用户名与密码是否正确<br>- 用户名与密码区分大小写<br><br>若您忘记了密码,请让工作人员删除您的旧密码并重新注册。
HTML ERRORS - AUTHENTICATION_FAIlED_401 || 认证失败。
HTML ERRORS - AUTHENTICATION_FAILED_401 || 认证失败。
HTML ERRORS - FORBIDDEN_403 || 禁止访问
HTML ERRORS - NO_SERVERS_404 || 无可执行此请求的在线服务器。
HTML ERRORS - NOT_FOUND_404 || 未找到

View File

@ -245,7 +245,7 @@ HTML ERRORS - ACCESS_DENIED_403 || Zugriff verweigert
HTML ERRORS - ANALYSIS_REFRESH || Plan wird aktualisiert...
HTML ERRORS - ANALYSIS_REFRESH_LONG || Plan wird ausgeführt. Es wird in ein paar Sekunden neu geladen.
HTML ERRORS - AUTH_FAIL_TIPS_401 || - Stelle sicher, dass du einen Account mit <b>/plan register</b> hinzugefügt hast.<br>- Überprüfe, ob Passwort und Benutzername korrekt sind<br>- Bei Benutzername und Passwort auf Groß- und Kleinschreibung achten! <br><br>- Wenn du dein Passwort vergessen hast, bitte ein Teammitglied deinen Account zu löschen und neu zu erstellen.
HTML ERRORS - AUTHENTICATION_FAIlED_401 || Authentifizierung fehlgeschlagen.
HTML ERRORS - AUTHENTICATION_FAILED_401 || Authentifizierung fehlgeschlagen.
HTML ERRORS - FORBIDDEN_403 || Verboten
HTML ERRORS - NO_SERVERS_404 || Keine Server online, die die Anfrage ausführen können.
HTML ERRORS - NOT_FOUND_404 || Nicht gefunden.

View File

@ -245,7 +245,7 @@ HTML ERRORS - ACCESS_DENIED_403 || Access Denied
HTML ERRORS - ANALYSIS_REFRESH || Analysis is being refreshed..
HTML ERRORS - ANALYSIS_REFRESH_LONG || Analysis is being run, refresh the page after a few seconds..
HTML ERRORS - AUTH_FAIL_TIPS_401 || - Ensure you have registered a user with <b>/plan register</b><br>- Check that the username and password are correct<br>- Username and password are case-sensitive<br><br>If you have forgotten your password, ask a staff member to delete your old user and re-register.
HTML ERRORS - AUTHENTICATION_FAIlED_401 || Authentication Failed.
HTML ERRORS - AUTHENTICATION_FAILED_401 || Authentication Failed.
HTML ERRORS - FORBIDDEN_403 || Forbidden
HTML ERRORS - NO_SERVERS_404 || No Servers online to perform the request.
HTML ERRORS - NOT_FOUND_404 || Not Found

View File

@ -244,7 +244,7 @@ HTML ERRORS - ACCESS_DENIED_403 || Pääsy Kielletty
HTML ERRORS - ANALYSIS_REFRESH || Analyysiä suoritetaan..
HTML ERRORS - ANALYSIS_REFRESH_LONG || Analyysiä suoritetaan, sivu päivittyy hetken kuluttua..
HTML ERRORS - AUTH_FAIL_TIPS_401 || - Varmista että olet rekisteröinyt käyttäjän komennolla <b>/plan register</b><br>- Tarkista että käyttäjänimi ja salaasana ovat oikein<br>- Nimi ja salasana ovat CASE SENSITIVE<br><br>Jos unohdit salasanasi, pyydä valvojia poistamaan käyttäjäsi ja uudelleenrekisteröidy.
HTML ERRORS - AUTHENTICATION_FAIlED_401 || Autentikaatio ei onnistunut.
HTML ERRORS - AUTHENTICATION_FAILED_401 || Autentikaatio ei onnistunut.
HTML ERRORS - FORBIDDEN_403 || Kielletty
HTML ERRORS - NO_SERVERS_404 || Ei palvelimia jolla toiminto voitaisiin suorittaa.
HTML ERRORS - NOT_FOUND_404 || Ei löytynyt

View File

@ -245,7 +245,7 @@ HTML ERRORS - ACCESS_DENIED_403 || Accès refusé.
HTML ERRORS - ANALYSIS_REFRESH || L'analyseur est en cours de rafraîchissement...
HTML ERRORS - ANALYSIS_REFRESH_LONG || L'analyse est en cours d'exécution, actualisez la page après quelques secondes....
HTML ERRORS - AUTH_FAIL_TIPS_401 || - Assurez-vous d'avoir enregistré un utilisateur avec :<b>'/plan register'.</b><br>- Vérifiez que le nom d'utilisateur et le mot de passe soient corrects.<br>- Le nom d'utilisateur et le mot de passe sont sensibles au format majuscule/minuscule.<br><br>Si vous avez oublié votre mot de passe, demandez à un membre du staff de supprimer votre ancien utilisateur puis de vous réinscrire.
HTML ERRORS - AUTHENTICATION_FAIlED_401 || Authentification échouée.
HTML ERRORS - AUTHENTICATION_FAILED_401 || Authentification échouée.
HTML ERRORS - FORBIDDEN_403 || Accès interdit.
HTML ERRORS - NO_SERVERS_404 || Aucun serveur en ligne pour exécuter la demande.
HTML ERRORS - NOT_FOUND_404 || Non trouvé.

View File

@ -245,7 +245,7 @@ HTML ERRORS - ACCESS_DENIED_403 || Access Denied
HTML ERRORS - ANALYSIS_REFRESH || Analysis is being refreshed..
HTML ERRORS - ANALYSIS_REFRESH_LONG || Analysis is being run, refresh the page after a few seconds..
HTML ERRORS - AUTH_FAIL_TIPS_401 || - Ensure you have registered a user with <b>/plan register</b><br>- Check that the username and password are correct<br>- Username and password are case-sensitive<br><br>If you have forgotten your password, ask a staff member to delete your old user and re-register.
HTML ERRORS - AUTHENTICATION_FAIlED_401 || Authentication Failed.
HTML ERRORS - AUTHENTICATION_FAILED_401 || Authentication Failed.
HTML ERRORS - FORBIDDEN_403 || Forbidden
HTML ERRORS - NO_SERVERS_404 || No Servers online to perform the request.
HTML ERRORS - NOT_FOUND_404 || Not Found

View File

@ -261,7 +261,7 @@ HTML ERRORS - ACCESS_DENIED_403 || アクセスが拒否され
HTML ERRORS - ANALYSIS_REFRESH || 分析結果に基づいてデータを更新中です・・・
HTML ERRORS - ANALYSIS_REFRESH_LONG || サーバーを分析中です・・・・<br>数秒後にページが更新されない場合、ページを更新して下さい
HTML ERRORS - AUTH_FAIL_TIPS_401 || - 登録したユーザーを<b>「/plan register 」</b>で確認できます。<br>- 入力したユーザー名とパスワードが正しいことを確認して下さい<br>- ユーザー名とパスワードは大文字と小文字が区別されています<br><br>パスワードを忘れた場合は、管理者に古いユーザーを削除して新しくユーザーを再登録するよう依頼して下さい
HTML ERRORS - AUTHENTICATION_FAIlED_401 || 認証に失敗しました
HTML ERRORS - AUTHENTICATION_FAILED_401 || 認証に失敗しました
HTML ERRORS - FORBIDDEN_403 || 閲覧禁止
HTML ERRORS - INSPECT_REFRESH || プレーヤページのリクエスト処理が実行中です・・
HTML ERRORS - INSPECT_REFRESH_LONG || ページは自動的に更新されます・・

View File

@ -21,6 +21,7 @@ import com.djrapitops.plan.data.time.WorldTimes;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import utilities.RandomData;
import utilities.TestConstants;
import java.util.List;
@ -42,21 +43,22 @@ class SessionTest {
@Test
void safeStartKeyConstructor() {
for (int i = 0; i < 10000; i++) {
Session session = new Session(null, serverUUID, System.currentTimeMillis(), null, null);
long expected = RandomData.randomLong(0, System.currentTimeMillis());
Session session = new Session(null, serverUUID, expected, null, null);
// Should not throw
session.getUnsafe(SessionKeys.START);
assertEquals(expected, session.getUnsafe(SessionKeys.START));
}
}
@Test
void safeStartKeyDBConstructor() {
for (int i = 0; i < 10000; i++) {
long time = System.currentTimeMillis();
Session session = new Session(-1, null, null, time, time + 1, 0, 0, 0);
long expected = RandomData.randomLong(0, System.currentTimeMillis());
Session session = new Session(-1, null, null, expected, expected + 1, 0, 0, 0);
// Should not throw
session.getUnsafe(SessionKeys.START);
assertEquals(expected, session.getUnsafe(SessionKeys.START));
}
}

View File

@ -1050,8 +1050,10 @@ public abstract class CommonDBTest {
}
@Test
public void indexCreationWorksWithoutErrors() {
db.executeTransaction(new CreateIndexTransaction());
public void indexCreationWorksWithoutErrors() throws Exception {
Transaction transaction = new CreateIndexTransaction();
db.executeTransaction(transaction).get(); // get to ensure transaction is finished
assertTrue(transaction.wasSuccessful());
}
@Test

View File

@ -20,12 +20,13 @@ import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@RunWith(JUnitPlatform.class)
class LocaleSystemTest {
@Test
void noIdentifierCollisions() {
// No Exception wanted
LocaleSystem.getIdentifiers();
assertDoesNotThrow(LocaleSystem::getIdentifiers);
}
}

View File

@ -32,6 +32,8 @@ import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertTrue;
@RunWith(JUnitPlatform.class)
class FileWatcherTest {
@ -63,6 +65,8 @@ class FileWatcherTest {
Awaitility.await()
.atMost(1, TimeUnit.SECONDS)
.until(methodWasCalled::get);
assertTrue(methodWasCalled.get());
} finally {
underTest.interrupt();
}

View File

@ -39,6 +39,10 @@ public class RandomData {
return ThreadLocalRandom.current().nextInt(rangeStart, rangeEnd);
}
public static long randomLong(long rangeStart, long rangeEnd) {
return ThreadLocalRandom.current().nextLong(rangeStart, rangeEnd);
}
public static String randomString(int size) {
return RandomStringUtils.randomAlphanumeric(size);
}

View File

@ -1,99 +0,0 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.settings.paths.WebserverSettings;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import rules.BukkitComponentMocker;
import rules.BungeeComponentMocker;
import rules.ComponentMocker;
import utilities.RandomData;
import java.util.UUID;
/**
* @author Rsl1122
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class BungeeBukkitConnectionTest {
@ClassRule
public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@ClassRule
public static ComponentMocker bukkitComponent = new BukkitComponentMocker(temporaryFolder);
@ClassRule
public static ComponentMocker bungeeComponent = new BungeeComponentMocker(temporaryFolder);
private final int TEST_PORT_NUMBER = RandomData.randomInt(9005, 9500);
@Rule
public ExpectedException thrown = ExpectedException.none();
private PlanSystem bukkitSystem;
private PlanSystem bungeeSystem;
@After
public void tearDown() {
System.out.println("------------------------------");
System.out.println("Disable");
System.out.println("------------------------------");
if (bukkitSystem != null) {
bukkitSystem.disable();
}
if (bungeeSystem != null) {
bungeeSystem.disable();
}
}
public void enable() throws Exception {
bukkitSystem = bukkitComponent.getPlanSystem();
bungeeSystem = bungeeComponent.getPlanSystem();
bukkitSystem.getConfigSystem().getConfig().set(WebserverSettings.PORT, TEST_PORT_NUMBER);
bungeeSystem.getConfigSystem().getConfig().set(WebserverSettings.PORT, 9250);
DBSystem dbSystem = bungeeSystem.getDatabaseSystem();
dbSystem.setActiveDatabase(dbSystem.getSqLiteFactory().usingDefaultFile());
bukkitSystem.enable();
bungeeSystem.enable();
UUID bukkitUUID = bukkitSystem.getServerInfo().getServerUUID();
UUID bungeeUUID = bungeeSystem.getServerInfo().getServerUUID();
System.out.println("------------------------------");
System.out.println("Enable Complete");
System.out.println("Bukkit: " + bukkitUUID);
System.out.println("Bungee: " + bungeeUUID);
System.out.println("------------------------------");
}
@Test
@Ignore("InfoRequestFactory not available via getters")
public void testRequest() throws Exception {
enable();
System.out.println("Sending request");
// bungeeSystem.getInfoSystem().getConnectionSystem().sendWideInfoRequest(new GenerateInspectPluginsTabRequest(infoSystem, infoRequestFactory, TestConstants.PLAYER_ONE_UUID));
}
}