Search in sources :

Example 1 with Platform

use of org.spongepowered.api.Platform in project SpongeCommon by SpongePowered.

the class TestImplementationModule method configure.

@Override
protected void configure() {
    super.configure();
    this.bind(Server.class).to(TestServer.class);
    this.bind(SpongeGame.class).to(TestGame.class);
    Platform platform = mock(Platform.class);
    PluginContainer mock = mock(PluginContainer.class);
    when(platform.getContainer(any())).thenReturn(mock);
    this.bind(Platform.class).toInstance(platform);
    PluginManager manager = mock(PluginManager.class);
    when(mock.getId()).thenReturn("sponge");
    when(manager.getPlugin(anyString())).thenReturn(Optional.of(mock));
    when(manager.fromInstance(any())).thenReturn(Optional.of(mock));
    this.bind(PluginManager.class).toInstance(manager);
    this.bind(EventManager.class).toInstance(mock(EventManager.class));
    this.bind(ChannelRegistrar.class).toInstance(mock(ChannelRegistrar.class));
}
Also used : PluginManager(org.spongepowered.api.plugin.PluginManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TestServer(org.spongepowered.common.test.TestServer) Server(org.spongepowered.api.Server) Platform(org.spongepowered.api.Platform) SpongePlatform(org.spongepowered.common.SpongePlatform) EventManager(org.spongepowered.api.event.EventManager) ChannelRegistrar(org.spongepowered.api.network.ChannelRegistrar) SpongeGame(org.spongepowered.common.SpongeGame)

Example 2 with Platform

use of org.spongepowered.api.Platform in project LanternServer by LanternPowered.

the class CommandVersion method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.description(t("commands.version.description")).executor((src, args) -> {
        final Platform platform = Lantern.getGame().getPlatform();
        PluginContainer plugin = platform.getContainer(Platform.Component.GAME);
        src.sendMessage(t("commands.version.minecraft", plugin.getVersion().orElse(UNKNOWN), LanternMinecraftVersion.CURRENT.getProtocol()));
        plugin = platform.getContainer(Platform.Component.IMPLEMENTATION);
        src.sendMessage(t("commands.version.implementation", plugin.getName(), plugin.getVersion().orElse(UNKNOWN)));
        plugin = platform.getContainer(Platform.Component.API);
        src.sendMessage(t("commands.version.api", plugin.getName(), plugin.getVersion().orElse(UNKNOWN)));
        return CommandResult.success();
    });
}
Also used : PluginContainer(org.spongepowered.api.plugin.PluginContainer) Platform(org.spongepowered.api.Platform)

Example 3 with Platform

use of org.spongepowered.api.Platform in project LanternServer by LanternPowered.

the class QueryHandler method handleFullStats.

private void handleFullStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    final LanternGame game = this.queryServer.getGame();
    final LanternServer server = game.getServer();
    final Platform platform = game.getPlatform();
    final PluginContainer api = platform.getContainer(Platform.Component.API);
    final PluginContainer impl = platform.getContainer(Platform.Component.IMPLEMENTATION);
    final PluginContainer mc = platform.getContainer(Platform.Component.GAME);
    final StringBuilder plugins = new StringBuilder().append(impl.getName()).append(" ").append(impl.getVersion()).append(" on ").append(api.getName()).append(" ").append(api.getVersion());
    if (this.showPlugins) {
        final List<PluginContainer> containers = new ArrayList<>(game.getPluginManager().getPlugins());
        containers.remove(api);
        containers.remove(impl);
        containers.remove(mc);
        char delim = ':';
        for (PluginContainer plugin : containers) {
            plugins.append(delim).append(' ').append(plugin.getName());
            delim = ';';
        }
    }
    final List<String> playerNames = server.getOnlinePlayers().stream().map(CommandSource::getName).collect(Collectors.toList());
    final Cause cause = Cause.of(EventContext.empty(), new SimpleRemoteConnection((InetSocketAddress) ctx.channel().remoteAddress(), null));
    final QueryServerEvent.Full event = SpongeEventFactory.createQueryServerEventFull(cause, (InetSocketAddress) ctx.channel().localAddress(), new HashMap<>(), "MINECRAFT", "SMP", getWorldName(), server.getMotd().toPlain(), playerNames, plugins.toString(), mc.getVersion().orElse("unknown"), server.getMaxPlayers(), Integer.MAX_VALUE, playerNames.size(), 0);
    final InetSocketAddress address = event.getAddress();
    final Map<String, Object> data = new LinkedHashMap<>();
    data.put("hostname", event.getMotd());
    data.put("gametype", event.getGameType());
    data.put("game_id", event.getGameId());
    data.put("version", event.getVersion());
    data.put("plugins", event.getPlugins());
    data.put("map", event.getMap());
    data.put("numplayers", event.getPlayerCount());
    data.put("maxplayers", event.getMaxPlayerCount());
    data.put("hostport", address.getPort());
    data.put("hostip", address.getHostString());
    event.getCustomValuesMap().entrySet().stream().filter(entry -> !data.containsKey(entry.getKey())).forEach(entry -> data.put(entry.getKey(), entry.getValue()));
    final ByteBuf buf = ctx.alloc().buffer();
    buf.writeByte(ACTION_STATS);
    buf.writeInt(sessionId);
    // constant: splitnum\x00\x80\x00
    buf.writeBytes(new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 });
    for (Entry<String, Object> e : data.entrySet()) {
        writeString(buf, e.getKey());
        writeString(buf, String.valueOf(e.getValue()));
    }
    buf.writeByte(0);
    // constant: \x01player_\x00\x00
    buf.writeBytes(new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 });
    for (Player player : game.getServer().getOnlinePlayers()) {
        writeString(buf, player.getName());
    }
    buf.writeByte(0);
    ctx.write(new DatagramPacket(buf, packet.sender()));
}
Also used : HashMap(java.util.HashMap) Platform(org.spongepowered.api.Platform) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) DatagramPacket(io.netty.channel.socket.DatagramPacket) PluginContainer(org.spongepowered.api.plugin.PluginContainer) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) LanternServer(org.lanternpowered.server.LanternServer) CommandSource(org.spongepowered.api.command.CommandSource) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) LanternGame(org.lanternpowered.server.game.LanternGame) StandardCharsets(java.nio.charset.StandardCharsets) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) World(org.spongepowered.api.world.World) Entry(java.util.Map.Entry) Player(org.spongepowered.api.entity.living.player.Player) EventContext(org.spongepowered.api.event.cause.EventContext) Player(org.spongepowered.api.entity.living.player.Player) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Platform(org.spongepowered.api.Platform) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) ByteBuf(io.netty.buffer.ByteBuf) LanternGame(org.lanternpowered.server.game.LanternGame) LinkedHashMap(java.util.LinkedHashMap) LanternServer(org.lanternpowered.server.LanternServer) Cause(org.spongepowered.api.event.cause.Cause) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 4 with Platform

use of org.spongepowered.api.Platform in project SpongeCommon by SpongePowered.

the class TimingsExport method reportTimings.

/**
 * Builds an XML report of the timings to be uploaded for parsing.
 *
 * @param sender Who to report to
 */
static void reportTimings(CommandSource sender) {
    Platform platform = SpongeImpl.getGame().getPlatform();
    JsonObjectBuilder builder = JSONUtil.objectBuilder().add("version", platform.getContainer(IMPLEMENTATION).getVersion().orElse(platform.getMinecraftVersion().getName() + "-DEV")).add("maxplayers", SpongeImpl.getGame().getServer().getMaxPlayers()).add("start", TimingsManager.timingStart / 1000).add("end", System.currentTimeMillis() / 1000).add("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);
    if (!TimingsManager.privacy) {
        builder.add("server", getServerName()).add("motd", Sponge.getServer().getMotd().toPlain()).add("online-mode", Sponge.getServer().getOnlineMode()).add("icon", SpongeImpl.getServer().getServerStatusResponse().getFavicon());
    }
    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    builder.add("system", JSONUtil.objectBuilder().add("timingcost", getCost()).add("name", System.getProperty("os.name")).add("version", System.getProperty("os.version")).add("jvmversion", System.getProperty("java.version")).add("arch", System.getProperty("os.arch")).add("maxmem", runtime.maxMemory()).add("cpu", runtime.availableProcessors()).add("runtime", ManagementFactory.getRuntimeMXBean().getUptime()).add("flags", RUNTIME_FLAG_JOINER.join(runtimeBean.getInputArguments())).add("gc", JSONUtil.mapArrayToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> {
        return JSONUtil.singleObjectPair(input.getName(), JSONUtil.arrayOf(input.getCollectionCount(), input.getCollectionTime()));
    })));
    Set<BlockType> blockTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();
    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        blockTypeSet.addAll(timingHistory.blockTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }
    // Current snapshot
    history[i] = new TimingHistory();
    blockTypeSet.addAll(history[i].blockTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);
    JsonObjectBuilder handlersBuilder = JSONUtil.objectBuilder();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.timed && !id.isSpecial()) {
                continue;
            }
            handlersBuilder.add(id.id, JSONUtil.arrayOf(group.id, id.name));
        }
    }
    builder.add("idmap", JSONUtil.objectBuilder().add("groups", JSONUtil.mapArrayToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> {
        return JSONUtil.singleObjectPair(group.id, group.name);
    })).add("handlers", handlersBuilder).add("worlds", JSONUtil.mapArrayToObject(TimingHistory.worldMap.entrySet(), (entry) -> {
        return JSONUtil.singleObjectPair(entry.getValue(), entry.getKey());
    })).add("tileentity", JSONUtil.mapArrayToObject(blockTypeSet, (blockType) -> {
        return JSONUtil.singleObjectPair(Block.getIdFromBlock((Block) blockType), blockType.getId());
    })).add("entity", JSONUtil.mapArrayToObject(entityTypeSet, (entityType) -> {
        if (entityType == EntityTypes.UNKNOWN) {
            return null;
        }
        return JSONUtil.singleObjectPair(TimingsPls.getEntityId(entityType), entityType.getId());
    })));
    // Information about loaded plugins
    builder.add("plugins", JSONUtil.mapArrayToObject(SpongeImpl.getGame().getPluginManager().getPlugins(), (plugin) -> {
        return JSONUtil.objectBuilder().add(plugin.getId(), JSONUtil.objectBuilder().add("version", plugin.getVersion().orElse("")).add("description", plugin.getDescription().orElse("")).add("website", plugin.getUrl().orElse("")).add("authors", AUTHOR_LIST_JOINER.join(plugin.getAuthors()))).build();
    }));
    // Information on the users Config
    builder.add("config", JSONUtil.objectBuilder().add("sponge", serializeConfigNode(SpongeImpl.getGlobalConfig().getRootNode())));
    new TimingsExport(sender, builder.build(), history).start();
}
Also used : SpongeImpl(org.spongepowered.common.SpongeImpl) HttpURLConnection(java.net.HttpURLConnection) JsonObject(com.google.gson.JsonObject) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HISTORY(co.aikar.timings.TimingsManager.HISTORY) URL(java.net.URL) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder) IMPLEMENTATION(org.spongepowered.api.Platform.Component.IMPLEMENTATION) Platform(org.spongepowered.api.Platform) JsonElement(com.google.gson.JsonElement) InetAddress(java.net.InetAddress) Block(net.minecraft.block.Block) EntityTypes(org.spongepowered.api.entity.EntityTypes) Text(org.spongepowered.api.text.Text) RconSource(org.spongepowered.api.command.source.RconSource) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) ManagementFactory(java.lang.management.ManagementFactory) TextColors(org.spongepowered.api.text.format.TextColors) OutputStream(java.io.OutputStream) RuntimeMXBean(java.lang.management.RuntimeMXBean) TextActions(org.spongepowered.api.text.action.TextActions) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) JSONUtil(co.aikar.util.JSONUtil) JsonArray(com.google.gson.JsonArray) BlockType(org.spongepowered.api.block.BlockType) Entry(java.util.Map.Entry) EntityType(org.spongepowered.api.entity.EntityType) GZIPOutputStream(java.util.zip.GZIPOutputStream) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) Platform(org.spongepowered.api.Platform) RuntimeMXBean(java.lang.management.RuntimeMXBean) EntityType(org.spongepowered.api.entity.EntityType) BlockType(org.spongepowered.api.block.BlockType) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder)

Example 5 with Platform

use of org.spongepowered.api.Platform in project Nucleus by NucleusPowered.

the class NucleusPlugin method getErrorMessage.

private List<Text> getErrorMessage() {
    List<Text> messages = Lists.newArrayList();
    messages.add(Text.of(TextColors.RED, "----------------------------"));
    messages.add(Text.of(TextColors.RED, "-  NUCLEUS FAILED TO LOAD  -"));
    messages.add(Text.of(TextColors.RED, "----------------------------"));
    addX(messages, 5);
    messages.add(Text.of(TextColors.RED, "----------------------------"));
    messages.add(Text.EMPTY);
    messages.add(Text.of(TextColors.RED, "Nucleus encountered an error during server start up and did not enable successfully. No commands, listeners or tasks are registered."));
    if (this.isServer) {
        messages.add(Text.of(TextColors.RED, "The server has been automatically whitelisted - this is to protect your server and players if you rely on some of Nucleus' functionality (such as fly states, etc.)"));
    }
    messages.add(Text.of(TextColors.RED, "The error that Nucleus encountered will be reproduced below for your convenience."));
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    if (isErrored == null) {
        messages.add(Text.of(TextColors.YELLOW, "No exception was saved."));
    } else {
        Throwable exception = isErrored;
        if (exception.getCause() != null && (exception instanceof QuickStartModuleLoaderException || exception instanceof QuickStartModuleDiscoveryException)) {
            exception = exception.getCause();
        }
        // Blegh, relocations
        if (exception instanceof IOException && exception.getCause().getClass().getName().contains(ConfigException.class.getSimpleName())) {
            exception = exception.getCause();
            messages.add(Text.of(TextColors.RED, "It appears that there is an error in your configuration file! The error is: "));
            messages.add(Text.of(TextColors.RED, exception.getMessage()));
            messages.add(Text.of(TextColors.RED, "Please correct this and restart your server."));
            messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
            messages.add(Text.of(TextColors.YELLOW, "(The error that was thrown is shown below)"));
        }
        try (StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw)) {
            exception.printStackTrace(pw);
            pw.flush();
            String[] stackTrace = sw.toString().split("(\r)?\n");
            for (String s : stackTrace) {
                messages.add(Text.of(TextColors.YELLOW, s));
            }
        } catch (IOException e) {
            exception.printStackTrace();
        }
    }
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    messages.add(Text.of(TextColors.RED, "If this error persists, check your configuration files and ensure that you have the latest version of Nucleus which matches the current version of the Sponge API."));
    messages.add(Text.of(TextColors.RED, "If you do, please report this error to the Nucleus team at https://github.com/NucleusPowered/Nucleus/issues"));
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    messages.add(Text.of(TextColors.YELLOW, "Server Information"));
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    messages.add(Text.of(TextColors.YELLOW, "Nucleus version: " + PluginInfo.VERSION + ", (Git: " + PluginInfo.GIT_HASH + ")"));
    Platform platform = Sponge.getPlatform();
    messages.add(Text.of(TextColors.YELLOW, "Minecraft version: " + platform.getMinecraftVersion().getName()));
    messages.add(Text.of(TextColors.YELLOW, String.format("Sponge Version: %s %s", platform.getContainer(Platform.Component.IMPLEMENTATION).getName(), platform.getContainer(Platform.Component.IMPLEMENTATION).getVersion().orElse("unknown"))));
    messages.add(Text.of(TextColors.YELLOW, String.format("Sponge API Version: %s %s", platform.getContainer(Platform.Component.API).getName(), platform.getContainer(Platform.Component.API).getVersion().orElse("unknown"))));
    messages.add(Text.EMPTY);
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    messages.add(Text.of(TextColors.YELLOW, "Installed Plugins"));
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    Sponge.getPluginManager().getPlugins().forEach(x -> messages.add(Text.of(TextColors.YELLOW, x.getName() + " (" + x.getId() + ") version " + x.getVersion().orElse("unknown"))));
    messages.add(Text.EMPTY);
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    messages.add(Text.of(TextColors.YELLOW, "- END NUCLEUS ERROR REPORT -"));
    messages.add(Text.of(TextColors.YELLOW, "----------------------------"));
    return messages;
}
Also used : QuickStartModuleDiscoveryException(uk.co.drnaylor.quickstart.exceptions.QuickStartModuleDiscoveryException) StringWriter(java.io.StringWriter) Platform(org.spongepowered.api.Platform) Text(org.spongepowered.api.text.Text) IOException(java.io.IOException) QuickStartModuleLoaderException(uk.co.drnaylor.quickstart.exceptions.QuickStartModuleLoaderException) PrintWriter(java.io.PrintWriter)

Aggregations

Platform (org.spongepowered.api.Platform)6 PluginContainer (org.spongepowered.api.plugin.PluginContainer)4 IOException (java.io.IOException)2 Entry (java.util.Map.Entry)2 Sponge (org.spongepowered.api.Sponge)2 CommandSource (org.spongepowered.api.command.CommandSource)2 Text (org.spongepowered.api.text.Text)2 HISTORY (co.aikar.timings.TimingsManager.HISTORY)1 JSONUtil (co.aikar.util.JSONUtil)1 JsonObjectBuilder (co.aikar.util.JSONUtil.JsonObjectBuilder)1 Joiner (com.google.common.base.Joiner)1 Sets (com.google.common.collect.Sets)1 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 ByteBuf (io.netty.buffer.ByteBuf)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)1 DatagramPacket (io.netty.channel.socket.DatagramPacket)1 BufferedWriter (java.io.BufferedWriter)1