SteamWar/BauSystem2.0
Archiviert
12
0

Remove reflections from startup

Signed-off-by: yoyosource <yoyosource@nidido.de>
Dieser Commit ist enthalten in:
yoyosource 2022-08-27 15:07:10 +02:00
Ursprung 8b9978102d
Commit 805e4de4e5
30 geänderte Dateien mit 316 neuen und 231 gelöschten Zeilen

Datei anzeigen

@ -0,0 +1,69 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
plugins {
id 'base'
id 'java'
}
group 'steamwar'
version '1.0'
compileJava.options.encoding = 'UTF-8'
sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceSets {
main {
java {
srcDirs = ['src/']
}
resources {
srcDirs = ['src/']
exclude '**/*.java', '**/*.kt'
}
}
}
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.22'
testCompileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.22'
implementation 'org.atteo.classindex:classindex:3.11'
testImplementation 'org.atteo.classindex:classindex:3.11'
annotationProcessor 'org.atteo.classindex:classindex:3.11'
testAnnotationProcessor 'org.atteo.classindex:classindex:3.11'
}
task buildResources {
doLast {
File from = new File("${buildDir}/classes/java/main/META-INF/annotations/de.steamwar.bausystem.linkage.ProcessorImplementation")
File to = new File("${buildDir}/classes/java/main/META-INF/services/javax.annotation.processing.Processor")
to.delete()
to.parentFile.mkdirs()
to.createNewFile()
for (String s : from.readLines()) {
to.append(s + "\n")
}
}
}
classes.finalizedBy(buildResources)

Datei anzeigen

@ -0,0 +1,139 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2022 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.linkage;
import lombok.SneakyThrows;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
@ProcessorImplementation
@SupportedAnnotationTypes("de.steamwar.bausystem.linkage.Linked")
public class LinkageProcessor extends AbstractProcessor {
private Messager messager;
private Writer writer;
private boolean processed = false;
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@SneakyThrows
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
writer = processingEnv.getFiler().createSourceFile("de.steamwar.bausystem.linkage.LinkageUtils").openWriter();
messager = processingEnv.getMessager();
}
@SneakyThrows
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (processed) return false;
processed = true;
List<String> fields = new ArrayList<>();
List<String> linkLines = new ArrayList<>();
List<String> unlinkLines = new ArrayList<>();
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Linked.class);
elements.addAll((Set)roundEnv.getElementsAnnotatedWith(Linked.Linkages.class));
for (Element element : elements) {
if (element.getKind() != ElementKind.CLASS) {
continue;
}
TypeElement typeElement = (TypeElement) element;
Linked[] linkeds = element.getAnnotationsByType(Linked.class);
if (linkeds.length == 0) {
continue;
}
System.out.println("Found element: " + typeElement.getQualifiedName().toString());
fields.add(typeElement.getQualifiedName().toString() + " " + typeElement.getSimpleName().toString() + " = new " + typeElement.getQualifiedName().toString() + "()");
Arrays.stream(linkeds).map(Linked::value).forEach(linkageType -> {
if (linkageType.toRun == null) return;
if (linkageType.className != null) {
if (!typeElement.getSuperclass().toString().equals(linkageType.className)) {
return;
}
}
if (linkageType.interfaceName != null) {
if (typeElement.getInterfaces().stream().noneMatch(i -> i.toString().equals(linkageType.interfaceName))) {
return;
}
}
(linkageType.unlink ? unlinkLines : linkLines).add(linkageType.toRun.replace("$", typeElement.getSimpleName().toString()));
});
List<VariableElement> variableElements = typeElement.getEnclosedElements().stream().filter(e -> e.getKind() == ElementKind.FIELD).map(e -> (VariableElement) e).filter(e -> {
return e.getAnnotation(LinkedInstance.class) != null;
}).collect(Collectors.toList());
if (variableElements.isEmpty()) {
continue;
}
for (VariableElement variableElement : variableElements) {
if (!variableElement.getModifiers().contains(Modifier.PUBLIC)) {
messager.printMessage(Diagnostic.Kind.ERROR, "Field " + variableElement.getSimpleName() + " must be public", variableElement);
continue;
}
if (variableElement.getModifiers().contains(Modifier.STATIC)) {
messager.printMessage(Diagnostic.Kind.ERROR, "Field " + variableElement.getSimpleName() + " must be non static", variableElement);
continue;
}
if (variableElement.getModifiers().contains(Modifier.FINAL)) {
messager.printMessage(Diagnostic.Kind.ERROR, "Field " + variableElement.getSimpleName() + " must be non final", variableElement);
continue;
}
linkLines.add(typeElement.getSimpleName().toString() + "." + variableElement.getSimpleName().toString() + " = " + ((DeclaredType) variableElement.asType()).asElement().getSimpleName().toString());
}
}
writer.write("package de.steamwar.bausystem.linkage;\n\n");
writer.write("public class LinkageUtils {\n");
for (String s : fields) {
writer.write(" public static " + s + ";\n");
}
writer.write("\n");
writer.write(" public static void link() {\n");
for (String s : linkLines) {
writer.write(" " + s + ";\n");
}
writer.write(" }\n");
writer.write("\n");
writer.write(" public static void unlink() {\n");
for (String s : unlinkLines) {
writer.write(" " + s + ";\n");
}
writer.write(" }\n");
writer.write("}\n");
writer.flush();
writer.close();
return true;
}
}

Datei anzeigen

@ -0,0 +1,55 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2022 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.linkage;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@AllArgsConstructor
public enum LinkageType {
// NORMAL
COMMAND(false, "$.setMessage(de.steamwar.bausystem.BauSystem.MESSAGE)", "de.steamwar.command.SWCommand"),
ENABLE_LINK(false, "$.enable()", null, "de.steamwar.bausystem.linkage.Enable"),
DISABLE_LINK(true, "$.disable()", null, "de.steamwar.bausystem.linkage.Disable"),
PLAIN(false),
LISTENER(false, "org.bukkit.Bukkit.getPluginManager().registerEvents($, de.steamwar.bausystem.BauSystem.getInstance())", null, "org.bukkit.event.Listener"),
UNLINK_LISTENER(true, "org.bukkit.event.HandlerList.unregisterAll($)", null, "org.bukkit.event.Listener"),
// SPECIFIC
BAU_GUI_ITEM(false, "de.steamwar.bausystem.features.gui.BauGUI.addItem($)", "de.steamwar.bausystem.linkage.specific.BauGuiItem"),
SCRIPT_COMMAND(false, "de.steamwar.bausystem.features.script.ScriptExecutor.SPECIAL_COMMANDS.add($)", null, "de.steamwar.bausystem.features.script.SpecialCommand"),
CONFIG_CONVERTER(false, "de.steamwar.bausystem.configplayer.Config.addConfigConverter($)", null, "de.steamwar.bausystem.configplayer.ConfigConverter"),
SCOREBOARD(false, null, null, "de.steamwar.bausystem.linkage.specific.ScoreboardItem"),
PANZERN(false, "de.steamwar.bausystem.features.slaves.panzern.PanzernAlgorithmLazyInit.add($)", null, "de.steamwar.bausystem.features.slaves.panzern.PanzernAlgorithm"),
SMART_PLACE(false, "de.steamwar.bausystem.features.smartplace.SmartPlaceListener.add($)", null, "de.steamwar.bausystem.features.smartplace.SmartPlaceBehaviour");
final boolean unlink;
String toRun = null;
String className = null;
String interfaceName = null;
LinkageType(boolean unlink, String toRun, String className) {
this.unlink = unlink;
this.toRun = toRun;
this.className = className;
}
}

Datei anzeigen

@ -0,0 +1,27 @@
/*
* Copyright 2019,2020,2021 yoyosource
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.steamwar.bausystem.linkage;
import org.atteo.classindex.IndexAnnotated;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@IndexAnnotated
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE})
public @interface ProcessorImplementation {
}

Datei anzeigen

@ -56,6 +56,9 @@ dependencies {
annotationProcessor 'org.atteo.classindex:classindex:3.11' annotationProcessor 'org.atteo.classindex:classindex:3.11'
testAnnotationProcessor 'org.atteo.classindex:classindex:3.11' testAnnotationProcessor 'org.atteo.classindex:classindex:3.11'
implementation project(":BauSystem_Linkage")
annotationProcessor project(":BauSystem_Linkage")
compileOnly 'org.spigotmc:spigot-api:1.19-R0.1-SNAPSHOT' compileOnly 'org.spigotmc:spigot-api:1.19-R0.1-SNAPSHOT'
compileOnly 'com.mojang:authlib:1.5.25' compileOnly 'com.mojang:authlib:1.5.25'
compileOnly 'io.netty:netty-all:4.1.68.Final' compileOnly 'io.netty:netty-all:4.1.68.Final'

Datei anzeigen

@ -29,7 +29,7 @@ import org.bukkit.entity.Player;
public class BauCommand extends SWCommand { public class BauCommand extends SWCommand {
@LinkedInstance @LinkedInstance
private InfoCommand infoCommand; public InfoCommand infoCommand;
public BauCommand() { public BauCommand() {
super("bau", "b", "gs"); super("bau", "b", "gs");

Datei anzeigen

@ -22,7 +22,7 @@ import static de.steamwar.bausystem.features.tpslimit.TPSWarpUtils.getTps;
public class InfoCommand extends SWCommand { public class InfoCommand extends SWCommand {
@LinkedInstance @LinkedInstance
private BauServer bauServer; public BauServer bauServer;
public InfoCommand() { public InfoCommand() {
super("bauinfo"); super("bauinfo");

Datei anzeigen

@ -54,7 +54,7 @@ public class DetonatorCommand extends SWCommand {
return wand; return wand;
} }
protected DetonatorCommand() { public DetonatorCommand() {
super("detonator", "dt"); super("detonator", "dt");
} }

Datei anzeigen

@ -29,7 +29,7 @@ import org.bukkit.entity.Player;
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public class BauGUICommand extends SWCommand { public class BauGUICommand extends SWCommand {
protected BauGUICommand() { public BauGUICommand() {
super("gui", "baugui", "g"); super("gui", "baugui", "g");
} }

Datei anzeigen

@ -30,7 +30,7 @@ import org.bukkit.inventory.ItemStack;
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public class HotbarCommand extends SWCommand { public class HotbarCommand extends SWCommand {
protected HotbarCommand() { public HotbarCommand() {
super("hotbar", "hb"); super("hotbar", "hb");
addDefaultHelpMessage("HOTBAR_HELP_GENERIC"); addDefaultHelpMessage("HOTBAR_HELP_GENERIC");
} }

Datei anzeigen

@ -29,7 +29,7 @@ import org.bukkit.entity.Player;
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public class LoaderCommand extends SWCommand { public class LoaderCommand extends SWCommand {
protected LoaderCommand() { public LoaderCommand() {
super("loader", "autoloader", "al"); super("loader", "autoloader", "al");
addDefaultHelpMessage("LOADER_HELP_OTHER"); addDefaultHelpMessage("LOADER_HELP_OTHER");
} }

Datei anzeigen

@ -27,7 +27,7 @@ import org.bukkit.entity.Player;
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public class LoadtimerCommand extends SWCommand { public class LoadtimerCommand extends SWCommand {
protected LoadtimerCommand() { public LoadtimerCommand() {
super("loadtimer", "lt", "stopuhr"); super("loadtimer", "lt", "stopuhr");
addDefaultHelpMessage("LOADTIMER_HELP_OVERVIEW"); addDefaultHelpMessage("LOADTIMER_HELP_OVERVIEW");
} }

Datei anzeigen

@ -40,7 +40,7 @@ import java.io.IOException;
public class ColorCommand extends SWCommand { public class ColorCommand extends SWCommand {
@LinkedInstance @LinkedInstance
private BauServer bauServer; public BauServer bauServer;
public ColorCommand() { public ColorCommand() {
super("color"); super("color");

Datei anzeigen

@ -50,10 +50,10 @@ import java.util.stream.Collectors;
public class RegionCommand extends SWCommand { public class RegionCommand extends SWCommand {
@LinkedInstance @LinkedInstance
private SelectCommand selectCommand; public SelectCommand selectCommand;
@LinkedInstance @LinkedInstance
private ColorCommand colorCommand; public ColorCommand colorCommand;
public RegionCommand() { public RegionCommand() {
super("region", "rg"); super("region", "rg");

Datei anzeigen

@ -42,7 +42,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class TNTListener implements Listener { public class TNTListener implements Listener {
@LinkedInstance @LinkedInstance
private CustomScriptManager customScriptManager; public CustomScriptManager customScriptManager;
@EventHandler @EventHandler
public void onExplode(EntityExplodeEvent event) { public void onExplode(EntityExplodeEvent event) {

Datei anzeigen

@ -37,7 +37,7 @@ import org.bukkit.inventory.ItemStack;
public class ResetBauGuiItem extends BauGuiItem { public class ResetBauGuiItem extends BauGuiItem {
@LinkedInstance @LinkedInstance
private ResetCommand resetCommand; public ResetCommand resetCommand;
public ResetBauGuiItem() { public ResetBauGuiItem() {
super(6); super(6);

Datei anzeigen

@ -37,7 +37,7 @@ import org.bukkit.inventory.ItemStack;
public class TestblockBauGuiItem extends BauGuiItem { public class TestblockBauGuiItem extends BauGuiItem {
@LinkedInstance @LinkedInstance
private TestblockCommand testblockCommand; public TestblockCommand testblockCommand;
public TestblockBauGuiItem() { public TestblockBauGuiItem() {
super(5); super(5);

Datei anzeigen

@ -25,7 +25,7 @@ public class ScriptCommand extends SWCommand {
} }
@LinkedInstance @LinkedInstance
private CustomScriptManager customScriptManager = null; public CustomScriptManager customScriptManager = null;
private List<String> loreBuilder(Player p, String... strings) { private List<String> loreBuilder(Player p, String... strings) {
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();

Datei anzeigen

@ -47,7 +47,7 @@ import java.util.Set;
public class ScriptEventListener implements Listener { public class ScriptEventListener implements Listener {
@LinkedInstance @LinkedInstance
private CustomScriptManager customScriptManager; public CustomScriptManager customScriptManager;
private static final Map<Player, Long> LAST_FS = new HashMap<>(); private static final Map<Player, Long> LAST_FS = new HashMap<>();

Datei anzeigen

@ -53,7 +53,7 @@ public class TechHiderCommand extends SWCommand implements Listener {
private Map<Region, Set<Player>> hidden = new HashMap<>(); private Map<Region, Set<Player>> hidden = new HashMap<>();
@LinkedInstance @LinkedInstance
private XrayCommand xrayCommand; public XrayCommand xrayCommand;
@Register(description = "TECHHIDER_HELP") @Register(description = "TECHHIDER_HELP")
public void toggleHider(Player player) { public void toggleHider(Player player) {

Datei anzeigen

@ -72,7 +72,7 @@ public class NoClipCommand extends SWCommand implements Listener {
private static final List<Player> NOCLIPS = new ArrayList<>(); private static final List<Player> NOCLIPS = new ArrayList<>();
private static final Map<Player, Long> LAST_TICKS = new HashMap<>(); private static final Map<Player, Long> LAST_TICKS = new HashMap<>();
protected NoClipCommand() { public NoClipCommand() {
super("noclip", "nc"); super("noclip", "nc");
BiFunction<Player, Object, Object> first = (player, o) -> { BiFunction<Player, Object, Object> first = (player, o) -> {

Datei anzeigen

@ -36,7 +36,7 @@ import java.util.Arrays;
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public class SlotCommand extends SWCommand { public class SlotCommand extends SWCommand {
protected SlotCommand() { public SlotCommand() {
super("slot", "s"); super("slot", "s");
addDefaultHelpMessage("OTHER_NOCLIP_SLOT_INFO"); addDefaultHelpMessage("OTHER_NOCLIP_SLOT_INFO");
} }

Datei anzeigen

@ -36,7 +36,7 @@ import org.bukkit.inventory.ItemStack;
public class DeclutterBauGuiItem extends BauGuiItem { public class DeclutterBauGuiItem extends BauGuiItem {
@LinkedInstance @LinkedInstance
private DeclutterCommand declutterCommand; public DeclutterCommand declutterCommand;
public DeclutterBauGuiItem() { public DeclutterBauGuiItem() {
super(30); super(30);

Datei anzeigen

@ -39,7 +39,7 @@ import java.util.Arrays;
public class KillAllBauGuiItem extends BauGuiItem { public class KillAllBauGuiItem extends BauGuiItem {
@LinkedInstance @LinkedInstance
private KillAllCommand killAllCommand; public KillAllCommand killAllCommand;
public KillAllBauGuiItem() { public KillAllBauGuiItem() {
super(32); super(32);

Datei anzeigen

@ -47,7 +47,7 @@ public class WarpCommand extends SWCommand implements Disable, Enable {
"add", "create", "delete", "list", "info", "gui" "add", "create", "delete", "list", "info", "gui"
}; };
protected WarpCommand() { public WarpCommand() {
super("warp"); super("warp");
} }
@ -132,7 +132,7 @@ public class WarpCommand extends SWCommand implements Disable, Enable {
@Linked(LinkageType.COMMAND) @Linked(LinkageType.COMMAND)
public static class WarpsLink extends SWCommand { public static class WarpsLink extends SWCommand {
protected WarpsLink() { public WarpsLink() {
super("warps"); super("warps");
} }

Datei anzeigen

@ -60,7 +60,7 @@ public class XrayCommand extends SWCommand implements Listener {
private Map<Region, Set<Player>> hidden = new HashMap<>(); private Map<Region, Set<Player>> hidden = new HashMap<>();
@LinkedInstance @LinkedInstance
private TechHiderCommand techHiderCommand; public TechHiderCommand techHiderCommand;
@Register(description = "XRAY_HELP") @Register(description = "XRAY_HELP")
public void toggleHider(Player player) { public void toggleHider(Player player) {

Datei anzeigen

@ -1,69 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.linkage;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.configplayer.Config;
import de.steamwar.bausystem.configplayer.ConfigConverter;
import de.steamwar.bausystem.features.gui.BauGUI;
import de.steamwar.bausystem.features.script.ScriptExecutor;
import de.steamwar.bausystem.features.script.SpecialCommand;
import de.steamwar.bausystem.features.slaves.panzern.PanzernAlgorithm;
import de.steamwar.bausystem.features.slaves.panzern.PanzernAlgorithmLazyInit;
import de.steamwar.bausystem.features.smartplace.SmartPlaceBehaviour;
import de.steamwar.bausystem.features.smartplace.SmartPlaceListener;
import de.steamwar.bausystem.linkage.specific.BauGuiItem;
import de.steamwar.bausystem.linkage.specific.ScoreboardItem;
import de.steamwar.command.SWCommand;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import java.util.function.Consumer;
import java.util.function.Predicate;
@RequiredArgsConstructor
public enum LinkageType {
// NORMAL
COMMAND(false, SWCommand.class::isAssignableFrom, o -> ((SWCommand) o).setMessage(BauSystem.MESSAGE)),
ENABLE_LINK(false, Enable.class::isAssignableFrom, o -> ((Enable) o).enable()),
DISABLE_LINK(true, Disable.class::isAssignableFrom, o -> ((Disable) o).disable()),
PLAIN(false, clazz -> true, o -> {}),
LISTENER(false, Listener.class::isAssignableFrom, o -> Bukkit.getPluginManager().registerEvents((Listener) o, BauSystem.getInstance())),
UNLINK_LISTENER(true, Listener.class::isAssignableFrom, o -> HandlerList.unregisterAll((Listener) o)),
// SPECIFIC
BAU_GUI_ITEM(false, BauGuiItem.class::isAssignableFrom, o -> BauGUI.addItem((BauGuiItem) o)),
SCRIPT_COMMAND(false, SpecialCommand.class::isAssignableFrom, o -> ScriptExecutor.SPECIAL_COMMANDS.add((SpecialCommand) o)),
CONFIG_CONVERTER(false, ConfigConverter.class::isAssignableFrom, o -> Config.addConfigConverter((ConfigConverter) o)),
SCOREBOARD(false, ScoreboardItem.class::isAssignableFrom, o -> {}),
PANZERN(false, PanzernAlgorithm.class::isAssignableFrom, o -> PanzernAlgorithmLazyInit.add((PanzernAlgorithm) o)),
SMART_PLACE(false, SmartPlaceBehaviour.class::isAssignableFrom, o -> SmartPlaceListener.add((SmartPlaceBehaviour) o));
final boolean unlink;
final Predicate<Class<?>> linkagePredicate;
final Consumer<Object> linkageConsumer;
}

Datei anzeigen

@ -1,139 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.linkage;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.configplayer.Config;
import de.steamwar.bausystem.utils.FlatteningWrapper;
import de.steamwar.bausystem.utils.NMSWrapper;
import de.steamwar.bausystem.utils.ProtocolWrapper;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
@UtilityClass
public class LinkageUtils {
private Map<Class<?>, Object> objectMap = new HashMap<>();
private List<Field> fieldsToLink = new ArrayList<>();
{
objectMap.put(Config.class, Config.getInstance());
objectMap.put(BauSystem.class, BauSystem.getInstance());
objectMap.put(FlatteningWrapper.class, FlatteningWrapper.impl);
objectMap.put(NMSWrapper.class, NMSWrapper.impl);
objectMap.put(ProtocolWrapper.class, ProtocolWrapper.impl);
}
public void link() {
internalLinkOrUnlink(false, Linked.class);
internalLinkFields();
}
public void unlink() {
internalLinkOrUnlink(true, Linked.class);
}
private void internalLinkOrUnlink(boolean unlink, Class<?> toLink) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(BauSystem.class.getResourceAsStream("/de.steamwar.bausystem/" + toLink.getTypeName().replace("$", "."))))) {
bufferedReader.lines().forEach(s -> {
try {
linkOrUnlink(Class.forName(s), unlink);
} catch (ClassNotFoundException e) {
// ignored
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e);
}
});
} catch (IOException e) {
Bukkit.shutdown();
} catch (NullPointerException e) {
// Ignored
}
}
private void internalLinkFields() {
for (Field field : fieldsToLink) {
LinkedInstance linkedInstance = field.getDeclaredAnnotation(LinkedInstance.class);
if (linkedInstance == null) {
continue;
}
Object object = objectMap.getOrDefault(field.getType(), null);
Object source = objectMap.getOrDefault(field.getDeclaringClass(), null);
try {
field.setAccessible(true);
field.set(source, object);
} catch (IllegalAccessException e) {
// Ignored
}
}
}
private void linkOrUnlink(Class<?> clazz, boolean unlink) {
Linked[] linkages = clazz.getDeclaredAnnotationsByType(Linked.class);
if (linkages.length == 0) {
return;
}
List<LinkageType> linkageTypeList = Arrays.stream(linkages).map(Linked::value).filter(linkageType -> linkageType.unlink == unlink).filter(linkageType -> linkageType.linkagePredicate.test(clazz)).collect(Collectors.toList());
if (linkageTypeList.isEmpty()) {
return;
}
if (unlink) {
Object object = objectMap.remove(clazz);
if (object == null) {
return;
}
linkageTypeList.forEach(linkageType -> linkageType.linkageConsumer.accept(object));
} else {
Object object = constructInstance(clazz);
objectMap.put(clazz, object);
linkageTypeList.forEach(linkageType -> linkageType.linkageConsumer.accept(object));
for (Field field : clazz.getDeclaredFields()) {
LinkedInstance linkedInstance = field.getDeclaredAnnotation(LinkedInstance.class);
if (linkedInstance == null) {
continue;
}
fieldsToLink.add(field);
}
}
}
private Object constructInstance(Class<?> clazz) {
try {
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true); //NOSONAR
return constructor.newInstance();
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
throw new SecurityException(e.getMessage(), e.getCause());
}
}
}