Java Code Examples for net.kyori.text.serializer.gson.GsonComponentSerializer

The following examples show how to use net.kyori.text.serializer.gson.GsonComponentSerializer. 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: GriefDefender   Source 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 2
Source Project: GriefDefender   Source 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 3
Source Project: Geyser   Source File: BasicItemTranslator.java    License: MIT License 5 votes vote down vote up
private String toJavaMessage(StringTag tag) {
    String message = tag.getValue();
    if (message == null) return null;
    if (message.startsWith("§r")) {
        message = message.replaceFirst("§r", "");
    }
    Component component = TextComponent.of(message);
    return GsonComponentSerializer.INSTANCE.serialize(component);
}
 
Example 4
Source Project: GriefDefender   Source File: SpongeUtil.java    License: MIT License 5 votes vote down vote up
public static Text getSpongeText(Component component) {
    if (component == null) {
        return Text.EMPTY;
    }
    //return Text.of(LegacyComponentSerializer.legacy().serialize((Component) component, '&'));
    return TextSerializers.JSON.deserialize(GsonComponentSerializer.INSTANCE.serialize(component));
}
 
Example 5
Source Project: PGM   Source 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 6
Source Project: Velocity   Source File: ConnectedPlayer.java    License: 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 7
Source Project: Velocity   Source File: ConnectedPlayer.java    License: MIT License 5 votes vote down vote up
/**
 * Handles unexpected disconnects.
 * @param server the server we disconnected from
 * @param disconnect the disconnect packet
 * @param safe whether or not we can safely reconnect to a new server
 */
public void handleConnectionException(RegisteredServer server, Disconnect disconnect,
    boolean safe) {
  if (!isActive()) {
    // If the connection is no longer active, it makes no sense to try and recover it.
    return;
  }

  Component disconnectReason = GsonComponentSerializer.INSTANCE.deserialize(
      disconnect.getReason());
  String plainTextReason = PASS_THRU_TRANSLATE.serialize(disconnectReason);
  if (connectedServer != null && connectedServer.getServerInfo().equals(server.getServerInfo())) {
    logger.error("{}: kicked from server {}: {}", this, server.getServerInfo().getName(),
        plainTextReason);
    handleConnectionException(server, disconnectReason, TextComponent.builder()
        .content("Kicked from " + server.getServerInfo().getName() + ": ")
        .color(TextColor.RED)
        .append(disconnectReason)
        .build(), safe);
  } else {
    logger.error("{}: disconnected while connecting to {}: {}", this,
        server.getServerInfo().getName(), plainTextReason);
    handleConnectionException(server, disconnectReason, TextComponent.builder()
        .content("Can't connect to server " + server.getServerInfo().getName() + ": ")
        .color(TextColor.RED)
        .append(disconnectReason)
        .build(), safe);
  }
}
 
Example 8
Source Project: Velocity   Source File: VelocityConfiguration.java    License: 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 9
Source Project: Velocity   Source File: VelocityBossBar.java    License: MIT License 5 votes vote down vote up
@Override
public void setTitle(Component title) {
  this.title = checkNotNull(title, "title");
  if (visible) {
    BossBar bar = new BossBar();
    bar.setUuid(uuid);
    bar.setAction(BossBar.UPDATE_NAME);
    bar.setName(GsonComponentSerializer.INSTANCE.serialize(title));
    sendToAffected(bar);
  }
}
 
Example 10
Source Project: Velocity   Source File: VelocityBossBar.java    License: MIT License 5 votes vote down vote up
private BossBar addPacket() {
  BossBar bossBar = new BossBar();
  bossBar.setUuid(uuid);
  bossBar.setAction(BossBar.ADD);
  bossBar.setName(GsonComponentSerializer.INSTANCE.serialize(title));
  bossBar.setColor(color.ordinal());
  bossBar.setOverlay(overlay.ordinal());
  bossBar.setPercent(percent);
  bossBar.setFlags(serializeFlags());
  return bossBar;
}
 
Example 11
Source Project: ViaVersion   Source File: VelocityCommandSender.java    License: MIT License 5 votes vote down vote up
@Override
public void sendMessage(String msg) {
    source.sendMessage(
            GsonComponentSerializer.INSTANCE.deserialize(
                    ComponentSerializer.toString(TextComponent.fromLegacyText(msg)) // Fixes links
            )
    );
}
 
Example 12
Source Project: ViaVersion   Source File: VelocityPlugin.java    License: MIT License 5 votes vote down vote up
@Override
public void sendMessage(UUID uuid, String message) {
    PROXY.getPlayer(uuid).ifPresent(it -> it.sendMessage(
            GsonComponentSerializer.INSTANCE.deserialize(
                    ComponentSerializer.toString(TextComponent.fromLegacyText(message)) // Fixes links
            )
    ));
}
 
Example 13
Source Project: ViaVersion   Source File: VelocityPlugin.java    License: MIT License 5 votes vote down vote up
@Override
public boolean kickPlayer(UUID uuid, String message) {
    return PROXY.getPlayer(uuid).map(it -> {
        it.disconnect(
                GsonComponentSerializer.INSTANCE.deserialize(
                        ComponentSerializer.toString(TextComponent.fromLegacyText(message))
                )
        );
        return true;
    }).orElse(false);
}
 
Example 14
Source Project: Geyser   Source File: MessageUtils.java    License: MIT License 4 votes vote down vote up
public static Component phraseJavaMessage(String message) {
    return GsonComponentSerializer.INSTANCE.deserialize(message);
}
 
Example 15
Source Project: Geyser   Source File: MessageUtils.java    License: MIT License 4 votes vote down vote up
public static String getJavaMessage(String message) {
    Component component = LegacyComponentSerializer.legacy().deserialize(message);
    return GsonComponentSerializer.INSTANCE.serialize(component);
}
 
Example 16
Source Project: GriefDefender   Source File: SpongeUtil.java    License: MIT License 4 votes vote down vote up
public static Component fromSpongeText(Text text) {
    return GsonComponentSerializer.INSTANCE.deserialize(TextSerializers.JSON.serialize(text));
}
 
Example 17
Source Project: TAB   Source File: Main.java    License: Apache License 2.0 4 votes vote down vote up
public static Object componentFromString(String json) {
	if (json == null) return null;
	return GsonComponentSerializer.INSTANCE.deserialize(json);
}
 
Example 18
Source Project: TAB   Source File: Main.java    License: Apache License 2.0 4 votes vote down vote up
public static String componentToString(Component component) {
	if (component == null) return null;
	return GsonComponentSerializer.INSTANCE.serialize(component);
}
 
Example 19
Source Project: spark   Source File: ForgeCommandSender.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public void sendMessage(Component message) {
    ITextComponent component = ITextComponent.Serializer.fromJson(GsonComponentSerializer.INSTANCE.serialize(message));
    super.delegate.sendMessage(component);
}
 
Example 20
Source Project: spark   Source File: FabricCommandSender.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public void sendMessage(Component message) {
    Text component = Text.Serializer.fromJson(GsonComponentSerializer.INSTANCE.serialize(message));
    super.delegate.sendMessage(component);
}
 
Example 21
Source Project: Velocity   Source File: Disconnect.java    License: MIT License 4 votes vote down vote up
public static Disconnect create(Component component) {
  Preconditions.checkNotNull(component, "component");
  return new Disconnect(GsonComponentSerializer.INSTANCE.serialize(component));
}
 
Example 22
Source Project: Velocity   Source File: HeaderAndFooter.java    License: MIT License 4 votes vote down vote up
public static HeaderAndFooter create(Component header, Component footer) {
  ComponentSerializer<Component, Component, String> json = GsonComponentSerializer.INSTANCE;
  return new HeaderAndFooter(json.serialize(header), json.serialize(footer));
}
 
Example 23
Source Project: Velocity   Source File: PlayerListItem.java    License: MIT License 4 votes vote down vote up
private static @Nullable Component readOptionalComponent(ByteBuf buf) {
  if (buf.readBoolean()) {
    return GsonComponentSerializer.INSTANCE.deserialize(ProtocolUtils.readString(buf));
  }
  return null;
}
 
Example 24
Source Project: Velocity   Source File: PlayerListItem.java    License: MIT License 4 votes vote down vote up
private void writeDisplayName(ByteBuf buf, @Nullable Component displayName) {
  buf.writeBoolean(displayName != null);
  if (displayName != null) {
    ProtocolUtils.writeString(buf, GsonComponentSerializer.INSTANCE.serialize(displayName));
  }
}
 
Example 25
Source Project: Velocity   Source File: Chat.java    License: MIT License 4 votes vote down vote up
public static Chat createClientbound(Component component, byte type, UUID sender) {
  Preconditions.checkNotNull(component, "component");
  return new Chat(GsonComponentSerializer.INSTANCE.serialize(component), type, sender);
}
 
Example 26
Source Project: Velocity   Source File: ConnectionRequestResults.java    License: MIT License 4 votes vote down vote up
public static Impl forDisconnect(Disconnect disconnect, RegisteredServer server) {
  Component deserialized = GsonComponentSerializer.INSTANCE.deserialize(disconnect.getReason());
  return forDisconnect(deserialized, server);
}
 
Example 27
Source Project: Velocity   Source File: ConnectionRequestResults.java    License: MIT License 4 votes vote down vote up
public static Impl forUnsafeDisconnect(Disconnect disconnect, RegisteredServer server) {
  Component deserialized = GsonComponentSerializer.INSTANCE.deserialize(disconnect.getReason());
  return new Impl(Status.SERVER_DISCONNECTED, deserialized, server, false);
}
 
Example 28
Source Project: helper   Source File: PacketScoreboard.java    License: MIT License 4 votes vote down vote up
static WrappedChatComponent toComponent(String text) {
    return WrappedChatComponent.fromJson(GsonComponentSerializer.INSTANCE.serialize(Text.fromLegacy(text)));
}