Skip to content

Commit 12b067e

Browse files
committed
[+] PluginLoader: load plugin
1 parent 49242d2 commit 12b067e

File tree

1 file changed

+57
-8
lines changed

1 file changed

+57
-8
lines changed

src/main/java/org/hydev/mcpm/client/injector/PluginLoader.java

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,73 @@
11
package org.hydev.mcpm.client.injector;
22

3+
import com.google.common.reflect.TypeToken;
4+
import org.bukkit.Bukkit;
5+
import org.bukkit.command.Command;
6+
import org.bukkit.command.PluginCommand;
7+
import org.bukkit.command.SimpleCommandMap;
8+
import org.bukkit.event.Event;
9+
import org.bukkit.plugin.InvalidDescriptionException;
10+
import org.bukkit.plugin.InvalidPluginException;
11+
import org.bukkit.plugin.Plugin;
12+
import org.bukkit.plugin.RegisteredListener;
13+
import org.hydev.mcpm.utils.PluginJarFile;
14+
315
import java.io.File;
16+
import java.io.IOException;
17+
import java.net.URLClassLoader;
18+
import java.util.*;
19+
20+
import static org.hydev.mcpm.utils.ReflectionUtils.getPrivateField;
21+
import static org.hydev.mcpm.utils.ReflectionUtils.setPrivateField;
422

523
/**
624
* TODO: Write a description for this class!
725
*
826
* @author Azalea (https://github.com/hykilpikonna)
927
* @since 2022-09-27
1028
*/
11-
public class PluginLoader
29+
public class PluginLoader implements LoadBoundary, UnloadBoundary, ReloadBoundary
1230
{
13-
/**
14-
* Dynamically load a local plugin through JVM reflections and classloader hacks
15-
*
16-
* @param jar Local jar file path
17-
*/
31+
@Override
32+
public void loadPlugin(String name) throws PluginNotFoundException
33+
{
34+
// 1. Find plugin file by name
35+
var nf = new PluginNotFoundException(name);
36+
var dir = new File("plugins");
37+
if (!dir.isDirectory()) throw nf;
38+
var file = Arrays.stream(Optional.ofNullable(dir.listFiles()).orElseThrow(() -> nf))
39+
.filter(f -> f.getName().endsWith(".jar"))
40+
.filter(f -> {
41+
try (var jf = new PluginJarFile(f))
42+
{
43+
return jf.readPluginYaml().getName().equalsIgnoreCase(name);
44+
}
45+
catch (IOException ignored) { return false; }
46+
}).findFirst().orElseThrow(() -> nf);
47+
48+
loadPlugin(file);
49+
}
50+
51+
@Override
1852
public void loadPlugin(File jar)
1953
{
20-
// TODO: Implement this
21-
throw new UnsupportedOperationException("TODO");
54+
// 2. Load plugin
55+
var pm = Bukkit.getPluginManager();
56+
try
57+
{
58+
var plugin = pm.loadPlugin(jar);
59+
assert plugin != null;
60+
61+
// 3. Call onLoad()
62+
plugin.onLoad();
63+
pm.enablePlugin(plugin);
64+
}
65+
catch (InvalidPluginException | InvalidDescriptionException e)
66+
{
67+
// These are errors indicating that the plugin we're trying to load is badly formatted.
68+
// There are nothing we can do.
69+
e.printStackTrace();
70+
}
2271
}
2372

2473
/**

0 commit comments

Comments
 (0)