Java Code Examples for net.kyori.text.serializer.legacy.LegacyComponentSerializer

The following examples show how to use net.kyori.text.serializer.legacy.LegacyComponentSerializer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Geyser   Author: GeyserMC   File: GeyserVelocityPingPassthrough.java    License: MIT License 6 votes vote down vote up
@Override
public GeyserPingInfo getPingInformation() {
    ProxyPingEvent event;
    try {
        event = server.getEventManager().fire(new ProxyPingEvent(FAKE_INBOUND_CONNECTION, ServerPing.builder()
                .description(server.getConfiguration().getMotdComponent()).onlinePlayers(server.getPlayerCount())
                .maximumPlayers(server.getConfiguration().getShowMaxPlayers()).build())).get();
    } catch (ExecutionException | InterruptedException e) {
        throw new RuntimeException(e);
    }
    GeyserPingInfo geyserPingInfo = new GeyserPingInfo(
            LegacyComponentSerializer.INSTANCE.serialize(event.getPing().getDescription(), '§'),
            event.getPing().getPlayers().orElseThrow(IllegalStateException::new).getOnline(),
            event.getPing().getPlayers().orElseThrow(IllegalStateException::new).getMax()
    );
    event.getPing().getPlayers().get().getSample().forEach(player -> {
        geyserPingInfo.addPlayer(player.getName());
    });
    return geyserPingInfo;
}
 
Example #2
Source Project: GriefDefender   Author: bloodmc   File: CommandEventHandler.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChatPost(AsyncPlayerChatEvent event) {
    final Player player = event.getPlayer();
    final Iterator<Player> iterator = event.getRecipients().iterator();

    while (iterator.hasNext()) {
        final Player receiver = iterator.next();
        if (receiver == player) {
            continue;
        }

        final GDPlayerData receiverData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(receiver.getWorld(), receiver.getUniqueId());
        if (receiverData.isRecordingChat()) {
            iterator.remove();
            final String s = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage());
            final Component message = LegacyComponentSerializer.legacy().deserialize(s, '&');
            final Component component = TextComponent.builder()
                    .append(TextComponent.builder()
                            .append(message)
                            .hoverEvent(HoverEvent.showText(TextComponent.of(formatter.format(Instant.now()))))
                            .build())
                    .build();
            receiverData.chatLines.add(component);
        }
    }
}
 
Example #3
Source Project: GriefDefender   Author: bloodmc   File: MessageDataConfig.java    License: MIT License 6 votes vote down vote up
public Component getMessage(String message, Map<String, Object> paramMap) {
    String rawMessage = this.messageMap.get(message);
    if (rawMessage == null) {
        // Should never happen but in case it does, return empty
        return TextComponent.empty();
    }
    for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
        final String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof Component) {
            value = LegacyComponentSerializer.legacy().serialize((Component) value, '&');
        }
        rawMessage = rawMessage.replace("{" + key + "}", value.toString()); 
    }

    return LegacyComponentSerializer.legacy().deserialize(rawMessage, '&');
}
 
Example #4
Source Project: GriefDefender   Author: bloodmc   File: ComponentConfigSerializer.java    License: MIT License 6 votes vote down vote up
@Override
public Component deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException {
    if (node.getString() == null || node.getString().isEmpty()) {
        return TextComponent.empty();
    }
    if (node.getString().contains("text=")) {
        // Try sponge data
        StringWriter writer = new StringWriter();

        GsonConfigurationLoader gsonLoader = GsonConfigurationLoader.builder()
                .setIndent(0)
                .setSink(() -> new BufferedWriter(writer))
                .setHeaderMode(HeaderMode.NONE)
                .build();

        try {
            gsonLoader.save(node);
        } catch (IOException e) {
            throw new ObjectMappingException(e);
        }
        return GsonComponentSerializer.INSTANCE.deserialize(writer.toString());
    }

    return LegacyComponentSerializer.legacy().deserialize(node.getString(), '&');
}
 
Example #5
Source Project: GriefDefender   Author: bloodmc   File: SignUtil.java    License: MIT License 6 votes vote down vote up
private static Consumer<CommandSender> createSaleConfirmationConsumer(CommandSender src, Claim claim, Sign sign, double price) {
    return confirm -> {
        claim.getEconomyData().setSalePrice(price);
        claim.getEconomyData().setForSale(true);
        claim.getEconomyData().setSaleSignPosition(VecHelper.toVector3i(sign.getLocation()));
        claim.getData().save();
        List<String> lines = new ArrayList<>(4);
        lines.add(ChatColor.translateAlternateColorCodes('&', "&7[&bGD&7-&1sell&7]"));
        lines.add(ChatColor.translateAlternateColorCodes('&', LegacyComponentSerializer.legacy().serialize(MessageCache.getInstance().ECONOMY_SIGN_SELL_DESCRIPTION)));
        lines.add(ChatColor.translateAlternateColorCodes('&', "&4$" + String.format("%.2f", price)));
        lines.add(ChatColor.translateAlternateColorCodes('&', LegacyComponentSerializer.legacy().serialize(MessageCache.getInstance().ECONOMY_SIGN_SELL_FOOTER)));

        for (int i = 0; i < lines.size(); i++) {
            sign.setLine(i, lines.get(i));
        }
        sign.update();
        final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ECONOMY_CLAIM_SALE_CONFIRMED,
                ImmutableMap.of("amount", price));
        GriefDefenderPlugin.sendMessage(src, message);
    };
}
 
Example #6
Source Project: GriefDefender   Author: bloodmc   File: SignUtil.java    License: MIT License 6 votes vote down vote up
public static void updateSignRentable(Claim claim, Sign sign) {
    if (!isRentSign(claim, sign)) {
        return;
    }


    final PaymentType paymentType = claim.getEconomyData().getPaymentType();
    List<String> colorLines = new ArrayList<>(4);
    colorLines.add(ChatColor.translateAlternateColorCodes('&', "&7[&bGD&7-&1rent&7]"));
    colorLines.add(ChatColor.translateAlternateColorCodes('&', LegacyComponentSerializer.legacy().serialize(MessageCache.getInstance().ECONOMY_SIGN_RENT_DESCRIPTION)));
    colorLines.add(ChatColor.translateAlternateColorCodes('&', "&4$" + claim.getEconomyData().getRentRate()));

    for (int i = 0; i < colorLines.size(); i++) {
        sign.setLine(i, colorLines.get(i));
    }
    sign.update();
}
 
Example #7
Source Project: GriefDefender   Author: bloodmc   File: MessageDataConfig.java    License: MIT License 6 votes vote down vote up
public Component getMessage(String message, Map<String, Object> paramMap) {
    String rawMessage = this.messageMap.get(message);
    if (rawMessage == null) {
        // Should never happen but in case it does, return empty
        return TextComponent.empty();
    }
    for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
        final String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof Component) {
            value = LegacyComponentSerializer.legacy().serialize((Component) value, '&');
        }
        rawMessage = rawMessage.replace("{" + key + "}", value.toString()); 
    }

    return LegacyComponentSerializer.legacy().deserialize(rawMessage, '&');
}
 
Example #8
Source Project: GriefDefender   Author: bloodmc   File: ComponentConfigSerializer.java    License: MIT License 6 votes vote down vote up
@Override
public Component deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException {
    if (node.getString() == null || node.getString().isEmpty()) {
        return TextComponent.empty();
    }
    if (node.getString().contains("text=")) {
        // Try sponge data
        StringWriter writer = new StringWriter();

        GsonConfigurationLoader gsonLoader = GsonConfigurationLoader.builder()
                .setIndent(0)
                .setSink(() -> new BufferedWriter(writer))
                .setHeaderMode(HeaderMode.NONE)
                .build();

        try {
            gsonLoader.save(node);
        } catch (IOException e) {
            throw new ObjectMappingException(e);
        }
        return GsonComponentSerializer.INSTANCE.deserialize(writer.toString());
    }

    return LegacyComponentSerializer.legacy().deserialize(node.getString(), '&');
}
 
Example #9
Source Project: SkinsRestorerX   Author: SkinsRestorer   File: SkinCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Subcommand("set") @CommandPermission("%skinSetOther")
@CommandCompletion("@players")
@Description("%helpSkinSetOther")
@Syntax("<target> <skin/url>")
public void onSkinSetOther(CommandSource source, OnlinePlayer target, String skin) {
    if (Config.PER_SKIN_PERMISSIONS && Config.USE_NEW_PERMISSIONS) {
        if (!source.hasPermission("skinsrestorer.skin." + skin)) {
            if (!getSenderName(source).equals(target.getPlayer().getUsername()) || (!source.hasPermission("skinsrestorer.ownskin") && !skin.equalsIgnoreCase(getSenderName(source)))) {
                source.sendMessage(LegacyComponentSerializer.legacy().deserialize(Locale.PLAYER_HAS_NO_PERMISSION_SKIN));
                return;
            }
        }
    }

    plugin.getService().execute(() -> {
        if (this.setSkin(source, target.getPlayer(), skin)) {
            if (!getSenderName(source).equals(target.getPlayer().getUsername())) {
                source.sendMessage(LegacyComponentSerializer.legacy().deserialize(Locale.ADMIN_SET_SKIN.replace("%player", target.getPlayer().getUsername())));
            }
        }
    });
}
 
Example #10
Source Project: DiscordSRV   Author: DiscordSRV   File: HerochatHook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void broadcastMessageToChannel(String channel, String message) {
    Channel chatChannel = getChannelByCaseInsensitiveName(channel);
    if (chatChannel == null) return; // no suitable channel found

    String plainMessage = LangUtil.Message.CHAT_CHANNEL_MESSAGE.toString()
            .replace("%channelcolor%", chatChannel.getColor().toString())
            .replace("%channelname%", chatChannel.getName())
            .replace("%channelnickname%", chatChannel.getNick())
            .replace("%message%", message);

    if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToMinecraft")) {
        chatChannel.sendRawMessage(LegacyComponentSerializer.legacy().serialize(MinecraftSerializer.INSTANCE.serialize(plainMessage)));
    } else {
        chatChannel.sendRawMessage(ChatColor.translateAlternateColorCodes('&', plainMessage));
    }

    PlayerUtil.notifyPlayersOfMentions(player ->
                    chatChannel.getMembers().stream()
                            .map(Chatter::getPlayer)
                            .collect(Collectors.toList())
                            .contains(player),
            message);
}
 
Example #11
Source Project: DiscordSRV   Author: DiscordSRV   File: LegendChatHook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void broadcastMessageToChannel(String channelName, String message) {
    Channel chatChannel = getChannelByCaseInsensitiveName(channelName);
    if (chatChannel == null) return; // no suitable channel found

    String plainMessage = LangUtil.Message.CHAT_CHANNEL_MESSAGE.toString()
            .replace("%channelcolor%", chatChannel.getColor())
            .replace("%channelname%", chatChannel.getName())
            .replace("%channelnickname%", chatChannel.getNickname())
            .replace("%message%", message);

    if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToMinecraft")) {
        chatChannel.sendMessage(LegacyComponentSerializer.legacy().serialize(MinecraftSerializer.INSTANCE.serialize(plainMessage)));
    } else {
        chatChannel.sendMessage(ChatColor.translateAlternateColorCodes('&', plainMessage));
    }

    PlayerUtil.notifyPlayersOfMentions(player -> chatChannel.getPlayersWhoCanSeeChannel().contains(player), message);
}
 
Example #12
Source Project: DiscordSRV   Author: DiscordSRV   File: LunaChatHook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void broadcastMessageToChannel(String channel, String message) {
    Channel chatChannel = LunaChat.getInstance().getLunaChatAPI().getChannel(channel);
    if (chatChannel == null) return; // no suitable channel found

    String plainMessage = LangUtil.Message.CHAT_CHANNEL_MESSAGE.toString()
            .replace("%channelcolor%", chatChannel.getColorCode())
            .replace("%channelname%", chatChannel.getName())
            .replace("%channelnickname%", (chatChannel.getAlias().equals(""))
                    ? chatChannel.getName() : chatChannel.getAlias())
            .replace("%message%", message);

    if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToMinecraft")) {
        chatChannel.sendMessage(null, "", LegacyComponentSerializer.legacy().serialize(MinecraftSerializer.INSTANCE.serialize(plainMessage)), true, "Discord");
    } else {
        chatChannel.sendMessage(null, "", ChatColor.translateAlternateColorCodes('&', plainMessage), true, "Discord");
    }

    PlayerUtil.notifyPlayersOfMentions(player ->
                    chatChannel.getMembers().stream()
                            .map(ChannelPlayer::getPlayer)
                            .collect(Collectors.toList())
                            .contains(player),
            message);
}
 
Example #13
Source Project: DiscordSRV   Author: DiscordSRV   File: FancyChatHook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void broadcastMessageToChannel(String channel, String message) {
    FancyChannel fancyChannel = FancyChatApi.getChannel(channel);

    if (fancyChannel == null) return; // no suitable channel found

    String plainMessage = LangUtil.Message.CHAT_CHANNEL_MESSAGE.toString()
            .replace("%channelcolor%", "")
            .replace("%channelname%", fancyChannel.getName())
            .replace("%channelnickname%", fancyChannel.getAlias())
            .replace("%message%", message);

    if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToMinecraft")) {
        FancyChatApi.sendMessage(LegacyComponentSerializer.legacy().serialize(MinecraftSerializer.INSTANCE.serialize(plainMessage)), fancyChannel);
    } else {
        FancyChatApi.sendMessage(ChatColor.translateAlternateColorCodes('&', plainMessage), fancyChannel);
    }
}
 
Example #14
Source Project: Geyser   Author: GeyserMC   File: BasicItemTranslator.java    License: MIT License 5 votes vote down vote up
private String toBedrockMessage(StringTag tag) {
    String message = tag.getValue();
    if (message == null) return null;
    TextComponent component = (TextComponent) MessageUtils.phraseJavaMessage(message);
    String legacy = LegacyComponentSerializer.legacy().serialize(component);
    if (hasFormatting(LegacyComponentSerializer.legacy().deserialize(legacy))) {
        return "§r" + legacy;
    }
    return legacy;
}
 
Example #15
Source Project: GriefDefender   Author: bloodmc   File: ComponentConfigSerializer.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(TypeToken<?> type, Component obj, ConfigurationNode node) throws ObjectMappingException {
    if (obj == TextComponent.empty()) {
        node.setValue("");
    } else {
        node.setValue(LegacyComponentSerializer.legacy().serialize(obj, '&'));
    }
}
 
Example #16
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimFarewell.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimfarewell")
@Description("Sets the farewell message of your claim.")
@Syntax("<message>|clear")
@Subcommand("claim farewell")
public void execute(Player player, String message) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    if (claim.allowEdit(player) != null) {
        GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().PERMISSION_EDIT_CLAIM);
        return;
    }

    TextComponent farewell = LegacyComponentSerializer.legacy().deserialize(message, '&');
    if (farewell == TextComponent.empty() || farewell.content().equals("clear")) {
        claim.getInternalClaimData().setFarewell(null);
    } else {
        claim.getInternalClaimData().setFarewell(farewell);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    Component resultMessage = null;
    if (!claim.getInternalClaimData().getFarewell().isPresent()) {
        resultMessage = MessageCache.getInstance().CLAIM_FAREWELL_CLEAR;
    } else {
        resultMessage = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_FAREWELL,
                ImmutableMap.of(
                "farewell", farewell));
    }
    TextAdapter.sendComponent(player, resultMessage);
}
 
Example #17
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimName.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimname")
@Syntax("<name>|clear")
@Description("Sets the name of your claim.")
@Subcommand("claim name")
public void execute(Player player, String name) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Component result = claim.allowEdit(player);
    if (result != null) {
        GriefDefenderPlugin.sendMessage(player, result);
        return;
    }

    if (!player.hasPermission(GDPermissions.USE_RESERVED_CLAIM_NAMES)) {
        final GriefDefenderConfig<?> activeConfig = GriefDefenderPlugin.getActiveConfig(player.getWorld().getUID());
        for (String str : activeConfig.getConfig().claim.reservedClaimNames) {
            if (FilenameUtils.wildcardMatch(name, str)) {
                GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_RESERVED_NAME);
                return;
            }
        }
    }

    final TextComponent text = LegacyComponentSerializer.legacy().deserialize(name, '&');
    if (text == TextComponent.empty() || text.content().equals("clear")) {
        claim.getInternalClaimData().setName(null);
    } else {
        claim.getInternalClaimData().setName(text);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_NAME,
            ImmutableMap.of(
            "name", text));
    GriefDefenderPlugin.sendMessage(player, message);
}
 
Example #18
Source Project: GriefDefender   Author: bloodmc   File: CommandTownTag.java    License: MIT License 5 votes vote down vote up
@CommandAlias("towntag")
@Description("Sets the tag of your town.")
@Syntax("<tag>")
@Subcommand("town tag")
public void execute(Player player, String tag) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    if (claim == null || !claim.isInTown()) {
        GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().TOWN_NOT_IN);
        return;
    }

    final GDClaim town = claim.getTownClaim();
    final Component result = town.allowEdit(player);
    if (result != null) {
        GriefDefenderPlugin.sendMessage(player, result);
        return;
    }

    TextComponent name = LegacyComponentSerializer.legacy().deserialize(tag, '&');
    if (name == TextComponent.empty() || name.content().equals("clear")) {
        town.getTownData().setTownTag(null);
    } else {
        town.getTownData().setTownTag(name);
    }

    town.getInternalClaimData().setRequiresSave(true);
    Component resultMessage = null;
    if (!claim.getTownData().getTownTag().isPresent()) {
        resultMessage = MessageCache.getInstance().TOWN_TAG_CLEAR;
    } else {
        resultMessage = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.TOWN_TAG,
                ImmutableMap.of(
                "tag", name));
    }
    TextAdapter.sendComponent(player, resultMessage);
}
 
Example #19
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimGreeting.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimgreeting")
@Description("Sets the greeting message of your claim.")
@Syntax("<message>|clear")
@Subcommand("claim greeting")
public void execute(Player player, String message) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Component result = claim.allowEdit(player);
    if (result != null) {
        GriefDefenderPlugin.sendMessage(player, result);
        return;
    }

    final TextComponent greeting = LegacyComponentSerializer.legacy().deserialize(message, '&');
    if (greeting == TextComponent.empty() || greeting.content().equals("clear")) {
        claim.getInternalClaimData().setGreeting(null);
    } else {
        claim.getInternalClaimData().setGreeting(greeting);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    Component resultMessage = null;
    if (!claim.getInternalClaimData().getGreeting().isPresent()) {
        resultMessage = MessageCache.getInstance().CLAIM_GREETING_CLEAR;
    } else {
        resultMessage = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_GREETING,
                ImmutableMap.of(
                "greeting", greeting));
    }
    TextAdapter.sendComponent(player, resultMessage);
}
 
Example #20
Source Project: GriefDefender   Author: bloodmc   File: ComponentConfigSerializer.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(TypeToken<?> type, Component obj, ConfigurationNode node) throws ObjectMappingException {
    if (obj == TextComponent.empty()) {
        node.setValue("");
    } else {
        node.setValue(LegacyComponentSerializer.legacy().serialize(obj, '&'));
    }
}
 
Example #21
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimFarewell.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimfarewell")
@Description("Sets the farewell message of your claim.")
@Syntax("<message>|clear")
@Subcommand("claim farewell")
public void execute(Player player, String message) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    if (claim.allowEdit(player) != null) {
        GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().PERMISSION_EDIT_CLAIM);
        return;
    }

    TextComponent farewell = LegacyComponentSerializer.legacy().deserialize(message, '&');
    if (farewell == TextComponent.empty() || farewell.content().equals("clear")) {
        claim.getInternalClaimData().setFarewell(null);
    } else {
        claim.getInternalClaimData().setFarewell(farewell);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    Component resultMessage = null;
    if (!claim.getInternalClaimData().getFarewell().isPresent()) {
        resultMessage = MessageCache.getInstance().CLAIM_FAREWELL_CLEAR;
    } else {
        resultMessage = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_FAREWELL,
                ImmutableMap.of(
                "farewell", farewell));
    }
    TextAdapter.sendComponent(player, resultMessage);
}
 
Example #22
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimName.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimname")
@Syntax("<name>|clear")
@Description("Sets the name of your claim.")
@Subcommand("claim name")
public void execute(Player player, String name) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Component result = claim.allowEdit(player);
    if (result != null) {
        GriefDefenderPlugin.sendMessage(player, result);
        return;
    }

    if (!player.hasPermission(GDPermissions.USE_RESERVED_CLAIM_NAMES)) {
        final GriefDefenderConfig<?> activeConfig = GriefDefenderPlugin.getActiveConfig(player.getWorld().getProperties());
        for (String str : activeConfig.getConfig().claim.reservedClaimNames) {
            if (FilenameUtils.wildcardMatch(name, str)) {
                GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_RESERVED_NAME);
                return;
            }
        }
    }

    final TextComponent text = LegacyComponentSerializer.legacy().deserialize(name, '&');
    if (text == TextComponent.empty() || text.content().equals("clear")) {
        claim.getInternalClaimData().setName(null);
    } else {
        claim.getInternalClaimData().setName(text);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_NAME,
            ImmutableMap.of(
            "name", text));
    GriefDefenderPlugin.sendMessage(player, message);
}
 
Example #23
Source Project: GriefDefender   Author: bloodmc   File: CommandClaimGreeting.java    License: MIT License 5 votes vote down vote up
@CommandAlias("claimgreeting")
@Description("Sets the greeting message of your claim.")
@Syntax("<message>|clear")
@Subcommand("claim greeting")
public void execute(Player player, String message) {
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Component result = claim.allowEdit(player);
    if (result != null) {
        GriefDefenderPlugin.sendMessage(player, result);
        return;
    }

    final TextComponent greeting = LegacyComponentSerializer.legacy().deserialize(message, '&');
    if (greeting == TextComponent.empty() || greeting.content().equals("clear")) {
        claim.getInternalClaimData().setGreeting(null);
    } else {
        claim.getInternalClaimData().setGreeting(greeting);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    claim.getInternalClaimData().save();
    Component resultMessage = null;
    if (!claim.getInternalClaimData().getGreeting().isPresent()) {
        resultMessage = MessageCache.getInstance().CLAIM_GREETING_CLEAR;
    } else {
        resultMessage = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_GREETING,
                ImmutableMap.of(
                "greeting", greeting));
    }
    TextAdapter.sendComponent(player, resultMessage);
}
 
Example #24
Source Project: PGM   Author: PGMDev   File: TextParser.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Parses text into a text component.
 *
 * <p>Accepts legacy formatting with "&" as the color character.
 *
 * <p>Accepts full qualified json strings as components.
 *
 * @param text The text.
 * @return A component.
 * @throws TextException If there is json present and it is invalid.
 */
public static Component parseComponent(String text) throws TextException {
  checkNotNull(text, "cannot parse component from null");

  if (text.startsWith("{") && text.endsWith("}")) {
    try {
      return GsonComponentSerializer.INSTANCE.deserialize(text);
    } catch (JsonSyntaxException e) {
      throw invalidFormat(text, Component.class, e);
    }
  }

  return LegacyComponentSerializer.legacy().deserialize(text, '&');
}
 
Example #25
Source Project: PGM   Author: PGMDev   File: TextTranslations.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets a translated legacy text.
 *
 * @param key A translation key.
 * @param sender A command sender, or null for the source locale.
 * @param args Optional array of arguments.
 * @return A legacy text.
 * @see #translate(Component, Locale) for the newer text system.
 */
@Deprecated
public static String translate(String key, @Nullable CommandSender sender, Object... args) {
  final Locale locale = sender == null ? SOURCE_LOCALE : sender.getLocale();
  final Component text =
      TranslatableComponent.of(
          key,
          Stream.of(args)
              .map(String::valueOf)
              .map(TextComponent::of)
              .collect(Collectors.toList()));

  return LegacyComponentSerializer.legacy().serialize(translate(text, locale));
}
 
Example #26
Source Project: PGM   Author: PGMDev   File: SidebarMatchModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private static String renderSidebarTitle(
    Collection<MapTag> tags, @Nullable Component gamemodeName) {
  final Component configTitle = PGM.get().getConfiguration().getMatchHeader();
  if (configTitle != null) return LegacyComponentSerializer.legacy().serialize(configTitle);
  if (gamemodeName != null) {
    String customGamemode = LegacyComponentSerializer.legacy().serialize(gamemodeName);
    if (!customGamemode.isEmpty()) return ChatColor.AQUA + customGamemode;
  }

  final List<String> gamemode =
      tags.stream()
          .filter(MapTag::isGamemode)
          .filter(tag -> !tag.isAuxiliary())
          .map(MapTag::getName)
          .collect(Collectors.toList());
  final List<String> auxiliary =
      tags.stream()
          .filter(MapTag::isGamemode)
          .filter(MapTag::isAuxiliary)
          .map(MapTag::getName)
          .collect(Collectors.toList());

  String title = "";

  if (gamemode.size() == 1) {
    title = gamemode.get(0);
  } else if (gamemode.size() >= 2) {
    title = "Objectives";
  }

  if (auxiliary.size() == 1) {
    title += (title.isEmpty() ? "" : " & ") + auxiliary.get(0);
  } else if (gamemode.isEmpty() && auxiliary.size() == 2) {
    title = auxiliary.get(0) + " & " + auxiliary.get(1);
  }

  return ChatColor.AQUA + (title.isEmpty() ? "Match" : title);
}
 
Example #27
Source Project: PGM   Author: PGMDev   File: ItemInfo.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Component getName() {
  if (getItem().hasItemMeta()) {
    String customName = getItem().getItemMeta().getDisplayName();
    if (customName != null) {
      return LegacyComponentSerializer.legacy().deserialize(customName);
    }
  }

  return MinecraftTranslations.getMaterial(getItem().getType());
}
 
Example #28
Source Project: PGM   Author: PGMDev   File: EntityInfo.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Component getName() {
  if (getCustomName() != null) {
    return LegacyComponentSerializer.legacy().deserialize(getCustomName());
  } else {
    return MinecraftTranslations.getEntity(getEntityType());
  }
}
 
Example #29
Source Project: PGM   Author: PGMDev   File: ProjectileInfo.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public net.kyori.text.Component getName() {
  if (customName != null) {
    return LegacyComponentSerializer.legacy().deserialize(customName);
  } else if (getProjectile() instanceof PotionInfo) {
    // PotionInfo.getName returns a potion name,
    // which doesn't work outside a potion death message.
    return TranslatableComponent.of("item.potion.name");
  } else {
    return getProjectile().getName();
  }
}
 
Example #30
Source Project: Velocity   Author: VelocityPowered   File: LegacyDisconnect.java    License: MIT License 5 votes vote down vote up
/**
 * Converts a modern server list ping response into an legacy disconnect packet.
 * @param response the server ping to convert
 * @param version the requesting clients' version
 * @return the disconnect packet
 */
public static LegacyDisconnect fromServerPing(ServerPing response,
    LegacyMinecraftPingVersion version) {
  Players players = response.getPlayers().orElse(FAKE_PLAYERS);

  switch (version) {
    case MINECRAFT_1_3:
      // Minecraft 1.3 and below use the section symbol as a delimiter. Accordingly, we must
      // remove all section symbols, along with fetching just the first line of an (unformatted)
      // MOTD.
      return new LegacyDisconnect(String.join(LEGACY_COLOR_CODE,
          cleanSectionSymbol(getFirstLine(PlainComponentSerializer.INSTANCE.serialize(response.getDescription()))),
          Integer.toString(players.getOnline()),
          Integer.toString(players.getMax())));
    case MINECRAFT_1_4:
    case MINECRAFT_1_6:
      // Minecraft 1.4-1.6 provide support for more fields, and additionally support color codes.
      return new LegacyDisconnect(String.join("\0",
          LEGACY_COLOR_CODE + "1",
          Integer.toString(response.getVersion().getProtocol()),
          response.getVersion().getName(),
          getFirstLine(LegacyComponentSerializer.legacy().serialize(response.getDescription())),
          Integer.toString(players.getOnline()),
          Integer.toString(players.getMax())
      ));
    default:
      throw new IllegalArgumentException("Unknown version " + version);
  }
}