Search in sources :

Example 11 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class EventManagerRegistrationTest method successfulRegistrationWithAsmDefinedClass.

@Test
public void successfulRegistrationWithAsmDefinedClass() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    final EventManager eventManager = new TestEventManager();
    final PluginContainer mock = Mockito.mock(PluginContainer.class);
    final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/spongepowered/common/test/event/BombDummy", null, "java/lang/Object", null);
    final MethodVisitor ctor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    ctor.visitCode();
    ctor.visitVarInsn(Opcodes.ALOAD, 0);
    ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    ctor.visitInsn(Opcodes.RETURN);
    ctor.visitMaxs(1, 1);
    final MethodVisitor el = writer.visitMethod(Opcodes.ACC_PUBLIC, "onBlockChange", "(Lorg/spongepowered/api/event/block/ChangeBlockEvent;)V", null, null);
    el.visitCode();
    el.visitAnnotation(Type.getDescriptor(Listener.class), true);
    el.visitInsn(Opcodes.RETURN);
    final MethodVisitor bomb = writer.visitMethod(Opcodes.ACC_PUBLIC, "throwup", "(Lcom/example/doesnt/Exist;)V", null, null);
    bomb.visitCode();
    bomb.visitInsn(Opcodes.RETURN);
    final DefineableClassLoader loader = new ReferencedDefinableClassLoader(this.getClass().getClassLoader());
    final Class<?> clazz = loader.defineClass("org.spongepowered.common.test.event.BombDummy", writer.toByteArray());
    final Object o = clazz.getConstructor().newInstance();
    eventManager.registerListeners(mock, o);
}
Also used : TestEventManager(org.spongepowered.common.test.TestEventManager) DefineableClassLoader(org.spongepowered.common.event.gen.DefineableClassLoader) PluginContainer(org.spongepowered.plugin.PluginContainer) Listener(org.spongepowered.api.event.Listener) ReferencedDefinableClassLoader(org.spongepowered.common.util.ReferencedDefinableClassLoader) EventManager(org.spongepowered.api.event.EventManager) TestEventManager(org.spongepowered.common.test.TestEventManager) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor) Test(org.junit.jupiter.api.Test)

Example 12 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class EventManagerRegistrationTest method wildcardCanRegister.

@Test
public void wildcardCanRegister() {
    final EventManager eventManager = new TestEventManager();
    final PluginContainer mock = Mockito.mock(PluginContainer.class);
    eventManager.registerListeners(mock, new Wildcard());
}
Also used : TestEventManager(org.spongepowered.common.test.TestEventManager) PluginContainer(org.spongepowered.plugin.PluginContainer) EventManager(org.spongepowered.api.event.EventManager) TestEventManager(org.spongepowered.common.test.TestEventManager) Test(org.junit.jupiter.api.Test)

Example 13 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class ScheduledTaskPhaseState method foldContextForThread.

@Override
public void foldContextForThread(final BasicPluginContext context, final TickTaskBridge returnValue) {
    @Nullable final Object source = context.getSource();
    final PluginContainer plugin = Objects.requireNonNull(context.container, "Scheduled Task has a null plugin!");
    returnValue.bridge$contextShift(((context1, stackFrame) -> {
        if (source != null) {
            stackFrame.pushCause(source);
        }
        stackFrame.pushCause(plugin);
    }));
}
Also used : Objects(java.util.Objects) TrackingUtil(org.spongepowered.common.event.tracking.TrackingUtil) PluginContainer(org.spongepowered.plugin.PluginContainer) Nullable(org.checkerframework.checker.nullness.qual.Nullable) TickTaskBridge(org.spongepowered.common.bridge.server.TickTaskBridge) PluginContainer(org.spongepowered.plugin.PluginContainer) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 14 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class SpongeServiceProvider method init.

// Service Discovery
/**
 * Discovers services by querying plugins with the
 * {@link ProvideServiceEvent}. To be called at the appropriate moment in
 * the lifecycle.
 */
public final void init() {
    if (!this.services.isEmpty()) {
        throw new IllegalStateException("Services have already been initialised");
    }
    final ServicesCategory.ServicePluginSubCategory servicePluginSubCategory = SpongeConfigs.getCommon().get().services.plugins;
    // This does NOT support third party service interfaces, only impls.
    for (final Service<?> candidate : this.servicesToSelect()) {
        // If the configuration file has a specific plugin ID, we look for it.
        final String pluginId = candidate.providePluginId(servicePluginSubCategory);
        final boolean isSpecific = !pluginId.isEmpty() && !pluginId.equals("?");
        final Class<?> serviceClass = candidate.getServiceClass();
        final String serviceName = serviceClass.getSimpleName();
        Registration<?> registration = null;
        if (isSpecific) {
            final Optional<PluginContainer> specificPluginContainer = Launch.instance().pluginManager().plugin(pluginId);
            if (specificPluginContainer.isPresent()) {
                registration = this.getSpecificRegistration(specificPluginContainer.get(), candidate);
                if (registration == null) {
                    final PrettyPrinter prettyPrinter = new PrettyPrinter(80).add("Service Registration Failed: %s (Service Not Provided)", serviceName).hr().addWrapped("Sponge is configured to obtain the service %s from the plugin with ID %s," + "however, that plugin did not provide any service implementation when " + "requested.", serviceName, pluginId).add().add("To fix this problem, do one of the following:").add().add(" * Check that the plugin %s can actually provide the service (check the plugin" + "   documentation if you need more assistance with that plugin).", pluginId).add(" * Set the config entry for this service to \"?\" to let Sponge find another " + "   plugin to provide the service.").add(" * Set the config entry for this service to the ID of another plugin that can" + "   provide the service.");
                    if (candidate.suppliesDefault()) {
                        prettyPrinter.add().add("Sponge will continue using the inbuilt default service.");
                    }
                    prettyPrinter.log(SpongeCommon.logger(), Level.ERROR);
                }
            } else {
                final PrettyPrinter prettyPrinter = new PrettyPrinter(80).add("Service Registration Failed: %s (Plugin Not Found)", serviceName).hr().addWrapped("Sponge is configured to obtain the service %s from the plugin with ID %s," + "however, that plugin isn't installed.", serviceName, pluginId).add().add("To fix this problem, do one of the following:").add().add(" * Install the plugin %s", pluginId).add(" * Set the config entry for this service to \"?\" to let Sponge find another " + "   plugin to provide the service.").add(" * Set the config entry for this service to the ID of another plugin that can" + "   provide the service.");
                if (candidate.suppliesDefault()) {
                    prettyPrinter.add().add("Sponge will continue using the inbuilt default service.");
                }
                prettyPrinter.log(SpongeCommon.logger(), Level.ERROR);
            }
        } else {
            final Collection<PluginContainer> toQuery = Launch.instance().pluginManager().plugins();
            registration = this.attemptRegistration(toQuery, candidate);
        }
        if (registration == null) {
            // If we don't have a registration, we try a Sponge one (which is lowest priority)
            registration = this.createRegistration(candidate, Launch.instance().commonPlugin());
        }
        // If after all that we have a registration, we... register it.
        if (registration != null) {
            this.services.put(candidate.getServiceClass(), registration);
            SpongeCommon.logger().info("Registered service [{}] to plugin '{}'.", registration.clazz.getSimpleName(), registration.pluginContainer.metadata().id());
        }
    }
}
Also used : PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) PluginContainer(org.spongepowered.plugin.PluginContainer) ServicesCategory(org.spongepowered.common.applaunch.config.common.ServicesCategory)

Example 15 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class PackTest method onRegisterCommand.

@Listener
public void onRegisterCommand(final RegisterCommandEvent<Command.Parameterized> event) {
    final Parameter.Value<PluginContainer> pluginContainerParameter = Parameter.plugin().key("plugin").build();
    final Parameter.Value<String> nameParameter = Parameter.string().key("name").build();
    final Parameter.Value<String> pathParameter = Parameter.string().key("path").build();
    event.register(this.plugin, Command.builder().addParameter(Parameter.firstOf(pluginContainerParameter, nameParameter)).addParameter(pathParameter).executor(exec -> {
        final Pack pack;
        final String path = exec.requireOne(pathParameter);
        if (exec.hasAny(pluginContainerParameter)) {
            pack = Sponge.server().packRepository().pack(exec.requireOne(pluginContainerParameter));
        } else {
            final String packName = exec.requireOne(nameParameter);
            pack = Sponge.server().packRepository().pack(packName).orElse(null);
            if (pack == null) {
                return CommandResult.error(Component.text("Pack " + packName + " does not exist."));
            }
        }
        try (final Resource resource = pack.contents().requireResource(PackType.server(), ResourcePath.of(pack.id(), path))) {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(resource.inputStream()));
            reader.lines().map(x -> Component.text(x.substring(0, Math.min(100, x.length())))).forEach(x -> exec.sendMessage(Identity.nil(), x));
        } catch (final Exception e) {
            e.printStackTrace();
            return CommandResult.error(Component.text("Could not locate: " + e.getMessage()));
        }
        return CommandResult.success();
    }).build(), "packtest");
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) PackType(org.spongepowered.api.resource.pack.PackType) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Pack(org.spongepowered.api.resource.pack.Pack) Command(org.spongepowered.api.command.Command) Identity(net.kyori.adventure.identity.Identity) Inject(com.google.inject.Inject) Sponge(org.spongepowered.api.Sponge) InputStreamReader(java.io.InputStreamReader) ResourcePath(org.spongepowered.api.resource.ResourcePath) Logger(org.apache.logging.log4j.Logger) PluginContainer(org.spongepowered.plugin.PluginContainer) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) Engine(org.spongepowered.api.Engine) Resource(org.spongepowered.api.resource.Resource) StartedEngineEvent(org.spongepowered.api.event.lifecycle.StartedEngineEvent) BufferedReader(java.io.BufferedReader) Listener(org.spongepowered.api.event.Listener) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) PluginContainer(org.spongepowered.plugin.PluginContainer) InputStreamReader(java.io.InputStreamReader) Resource(org.spongepowered.api.resource.Resource) BufferedReader(java.io.BufferedReader) Parameter(org.spongepowered.api.command.parameter.Parameter) Pack(org.spongepowered.api.resource.pack.Pack) Listener(org.spongepowered.api.event.Listener)

Aggregations

PluginContainer (org.spongepowered.plugin.PluginContainer)22 NonNull (org.checkerframework.checker.nullness.qual.NonNull)6 Collection (java.util.Collection)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 Component (net.kyori.adventure.text.Component)4 EventManager (org.spongepowered.api.event.EventManager)4 PluginMetadata (org.spongepowered.plugin.metadata.PluginMetadata)4 ArrayList (java.util.ArrayList)3 Optional (java.util.Optional)3 Identity (net.kyori.adventure.identity.Identity)3 TextComponent (net.kyori.adventure.text.TextComponent)3 Nullable (org.checkerframework.checker.nullness.qual.Nullable)3 Test (org.junit.jupiter.api.Test)3 Sponge (org.spongepowered.api.Sponge)3 Command (org.spongepowered.api.command.Command)3 CommandResult (org.spongepowered.api.command.CommandResult)3 Parameter (org.spongepowered.api.command.parameter.Parameter)3 RefreshGameEvent (org.spongepowered.api.event.lifecycle.RefreshGameEvent)3 SpongeEventManager (org.spongepowered.common.event.manager.SpongeEventManager)3