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

The following examples show how to use net.kyori.text.serializer.legacy.LegacyComponentSerializer. 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 File: SkinCommand.java    From SkinsRestorerX with 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 #2
Source File: LunaChatHook.java    From DiscordSRV with 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 #3
Source File: LegendChatHook.java    From DiscordSRV with 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 #4
Source File: HerochatHook.java    From DiscordSRV with 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 #5
Source File: ComponentConfigSerializer.java    From GriefDefender with 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 #6
Source File: MessageDataConfig.java    From GriefDefender with 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 #7
Source File: SignUtil.java    From GriefDefender with 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 #8
Source File: FancyChatHook.java    From DiscordSRV with 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 #9
Source File: SignUtil.java    From GriefDefender with 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 #10
Source File: ComponentConfigSerializer.java    From GriefDefender with 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 #11
Source File: MessageDataConfig.java    From GriefDefender with 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 #12
Source File: CommandEventHandler.java    From GriefDefender with 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 #13
Source File: GeyserVelocityPingPassthrough.java    From Geyser with 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 #14
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void sendMessage(Component component, MessagePosition position) {
  Preconditions.checkNotNull(component, "component");
  Preconditions.checkNotNull(position, "position");

  byte pos = (byte) position.ordinal();
  String json;
  if (position == MessagePosition.ACTION_BAR) {
    if (getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_11) >= 0) {
      // We can use the title packet instead.
      TitlePacket pkt = new TitlePacket();
      pkt.setAction(TitlePacket.SET_ACTION_BAR);
      pkt.setComponent(GsonComponentSerializer.INSTANCE.serialize(component));
      minecraftConnection.write(pkt);
      return;
    } else {
      // Due to issues with action bar packets, we'll need to convert the text message into a
      // legacy message and then inject the legacy text into a component... yuck!
      JsonObject object = new JsonObject();
      object.addProperty("text", LegacyComponentSerializer.legacy().serialize(component));
      json = object.toString();
    }
  } else {
    json = GsonComponentSerializer.INSTANCE.serialize(component);
  }

  Chat chat = new Chat();
  chat.setType(pos);
  chat.setMessage(json);
  minecraftConnection.write(chat);
}
 
Example #15
Source File: LegacyDisconnect.java    From Velocity with 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);
  }
}
 
Example #16
Source File: CommandLink.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
private static void executeAsync(Player sender, AccountLinkManager manager) {
    // prevent people from generating multiple link codes then claiming them all at once to get multiple rewards
    new ArrayList<>(manager.getLinkingCodes().entrySet()).stream()
            .filter(entry -> entry.getValue().equals(sender.getUniqueId()))
            .forEach(match -> manager.getLinkingCodes().remove(match.getKey()));

    if (manager.getDiscordId(sender.getUniqueId()) != null) {
        sender.sendMessage(ChatColor.AQUA + LangUtil.InternalMessage.ACCOUNT_ALREADY_LINKED.toString());
    } else {
        String code = manager.generateCode(sender.getUniqueId());

        TextComponent component = LegacyComponentSerializer.legacyLinking().deserialize(
                LangUtil.Message.CODE_GENERATED.toString()
                        .replace("%code%", code)
                        .replace("%botname%", DiscordSRV.getPlugin().getMainGuild().getSelfMember().getEffectiveName()),
                '&'
        );
        String clickToCopyCode = LangUtil.Message.CLICK_TO_COPY_CODE.toString();
        if (StringUtils.isNotBlank(clickToCopyCode)) {
            component = component.clickEvent(ClickEvent.copyToClipboard(code))
                    .hoverEvent(HoverEvent.showText(
                            LegacyComponentSerializer.legacy().deserialize(
                                    clickToCopyCode,
                                    '&'
                            )
                    ));
        }
        TextAdapter.sendComponent(sender, component);
    }
}
 
Example #17
Source File: ProjectileInfo.java    From PGM with 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 #18
Source File: EntityInfo.java    From PGM with 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 #19
Source File: ItemInfo.java    From PGM with 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 #20
Source File: SidebarMatchModule.java    From PGM with 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 #21
Source File: TextTranslations.java    From PGM with 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 #22
Source File: VelocityConfiguration.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Returns the proxy's MOTD.
 *
 * @return the MOTD
 */
@Override
public Component getMotdComponent() {
  if (motdAsComponent == null) {
    if (motd.startsWith("{")) {
      motdAsComponent = GsonComponentSerializer.INSTANCE.deserialize(motd);
    } else {
      motdAsComponent = LegacyComponentSerializer.legacy().deserialize(motd, '&');
    }
  }
  return motdAsComponent;
}
 
Example #23
Source File: BasicItemTranslator.java    From Geyser with 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 #24
Source File: CommandClaimGreeting.java    From GriefDefender with 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 #25
Source File: ComponentConfigSerializer.java    From GriefDefender with 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 #26
Source File: CommandClaimFarewell.java    From GriefDefender with 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 #27
Source File: CommandClaimName.java    From GriefDefender with 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 #28
Source File: CommandTownTag.java    From GriefDefender with 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 #29
Source File: CommandClaimGreeting.java    From GriefDefender with 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 #30
Source File: ComponentConfigSerializer.java    From GriefDefender with 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, '&'));
    }
}