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

The following examples show how to use net.kyori.text.serializer.gson.GsonComponentSerializer. 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: 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 #2
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 #3
Source File: VelocityPlugin.java    From ViaVersion with 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 #4
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 #5
Source File: ConnectedPlayer.java    From Velocity with 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 #6
Source File: BasicItemTranslator.java    From Geyser with 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 #7
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 #8
Source File: VelocityBossBar.java    From Velocity with 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 #9
Source File: VelocityBossBar.java    From Velocity with 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 #10
Source File: TextParser.java    From PGM with 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 #11
Source File: VelocityCommandSender.java    From ViaVersion with 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 File: SpongeUtil.java    From GriefDefender with 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 #13
Source File: VelocityPlugin.java    From ViaVersion with 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 #14
Source File: PacketScoreboard.java    From helper with MIT License 4 votes vote down vote up
static WrappedChatComponent toComponent(String text) {
    return WrappedChatComponent.fromJson(GsonComponentSerializer.INSTANCE.serialize(Text.fromLegacy(text)));
}
 
Example #15
Source File: ConnectionRequestResults.java    From Velocity with 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 #16
Source File: ConnectionRequestResults.java    From Velocity with 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 #17
Source File: PlayerListItem.java    From Velocity with 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 #18
Source File: Chat.java    From Velocity with 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 #19
Source File: PlayerListItem.java    From Velocity with 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 #20
Source File: HeaderAndFooter.java    From Velocity with 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 #21
Source File: Disconnect.java    From Velocity with 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 File: FabricCommandSender.java    From spark with 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 #23
Source File: ForgeCommandSender.java    From spark with 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 #24
Source File: Main.java    From TAB with 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 #25
Source File: Main.java    From TAB with 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 #26
Source File: SpongeUtil.java    From GriefDefender with MIT License 4 votes vote down vote up
public static Component fromSpongeText(Text text) {
    return GsonComponentSerializer.INSTANCE.deserialize(TextSerializers.JSON.serialize(text));
}
 
Example #27
Source File: MessageUtils.java    From Geyser with 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 #28
Source File: MessageUtils.java    From Geyser with MIT License 4 votes vote down vote up
public static Component phraseJavaMessage(String message) {
    return GsonComponentSerializer.INSTANCE.deserialize(message);
}