org.spongepowered.api.text.serializer.TextSerializers Java Examples

The following examples show how to use org.spongepowered.api.text.serializer.TextSerializers. 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: MeExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	String message = ctx.<String> getOne("message").get();
	Text finalMessage = Text.builder()
		.append(Text.of(TextColors.DARK_GRAY, "* ", TextColors.DARK_RED, src.getName(), TextColors.GREEN, " "))
		.append(TextSerializers.formattingCode('&').deserialize(message))
		.build();

	if (src instanceof Player && EssentialCmds.muteList.contains(((Player) src).getUniqueId()))
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You are muted!"));
		return;
	}

	MessageChannel.TO_ALL.send(finalMessage);
}
 
Example #2
Source File: LoanModule.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void postInitialization(Logger logger, Object plugin) {
    // Create loan manager
    loanManager = new LoanManager(this);
    // Register listeners
    Sponge.getEventManager().registerListeners(plugin, new LoanListener(this));
    // Register commands
    CommandLoader.registerCommands(plugin, TextSerializers.FORMATTING_CODE.serialize(messages.getMessage("command.invalidsource")),
            new LoanCommand(),
            new LoanBalanceCommand(this),
            new LoanPayCommand(this),
            new LoanTakeCommand(this),
            new LoanAcceptCommand(this),
            new LoanDenyCommand(this)
    );
}
 
Example #3
Source File: ChatConfigImpl.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
public void reload()
{
	//Chat
	this.chatPrefixType = this.configuration.getString("tag", "faction-prefix");
	this.suppressOtherFactionsMessagesWhileInTeamChat = this.configuration.getBoolean(false, "suppress-other-factions-messages-while-in-team-chat");
	this.displayProtectionSystemMessages = this.configuration.getBoolean(true, "display-protection-system-messages");
	this.canColorTags = this.configuration.getBoolean(true, "colored-tags-allowed");
	this.factionStartPrefix = TextSerializers.FORMATTING_CODE.deserialize(configuration.getString("[", "faction-prefix-start"));
	this.factionEndPrefix = TextSerializers.FORMATTING_CODE.deserialize(configuration.getString("]", "faction-prefix-end"));
	this.isFactionPrefixFirstInChat = this.configuration.getBoolean(true, "faction-prefix-first-in-chat");
	this.nonFactionPlayerPrefix = TextSerializers.FORMATTING_CODE.deserialize(configuration.getString("", "non-faction-player-prefix"));
	this.showFactionEnterPhrase = this.configuration.getBoolean(true, "show-faction-enter-phrase");

	this.visibleRanks = new HashMap<>();
	final Set<FactionMemberType> globalRanks = new HashSet<>();
	final Set<FactionMemberType> allianceRanks = new HashSet<>();
	final Set<FactionMemberType> factionRanks = new HashSet<>();
	globalRanks.addAll(this.configuration.getListOfStrings(Collections.emptyList(), "visible-ranks", "global-chat").stream().map(FactionMemberType::valueOf).collect(Collectors.toSet()));
	allianceRanks.addAll(this.configuration.getListOfStrings(Collections.emptyList(), "visible-ranks", "alliance-chat").stream().map(FactionMemberType::valueOf).collect(Collectors.toSet()));
	factionRanks.addAll(this.configuration.getListOfStrings(Collections.emptyList(), "visible-ranks", "faction-chat").stream().map(FactionMemberType::valueOf).collect(Collectors.toSet()));
	this.visibleRanks.put(ChatEnum.GLOBAL, globalRanks);
	this.visibleRanks.put(ChatEnum.ALLIANCE, allianceRanks);
	this.visibleRanks.put(ChatEnum.FACTION, factionRanks);
	this.visibleRanks = ImmutableMap.copyOf(this.visibleRanks);
}
 
Example #4
Source File: CachedVShop.java    From Web-API with MIT License 6 votes vote down vote up
public CachedVShop(NPCguard shop) {
        super(shop);

        this.uid = shop.getIdentifier().toString();
        this.name = TextSerializers.FORMATTING_CODE.serialize(shop.getDisplayName());
        this.location = new CachedLocation(shop.getLoc());
        this.rotation = shop.getRot().getY();
        this.entityType = new CachedCatalogType<>(shop.getNpcType());
        this.entityVariant = shop.getVariantName();
        this.owner = shop.getShopOwner().orElse(null);
//		this.isPlayerShop = shop.getShopOwner().isPresent();

        Optional<Location<World>> stock = shop.getStockContainer();
        this.stockContainer = stock.map(CachedLocation::new).orElse(null);

        InvPrep inv = shop.getPreparator();
        this.stockItems = new LinkedList<>();
        int s = inv.size();
        for (int i = 0; i < s; i++)
            stockItems.add(new CachedStockItem(inv.getItem(i), i, getUID()));
    }
 
Example #5
Source File: SayExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	String message = ctx.<String> getOne("message").get();
	Text finalMessage = Text.builder()
		.append(Text.of(TextColors.DARK_GRAY, "[", TextColors.DARK_RED, src.getName(), TextColors.DARK_GRAY, "]", TextColors.GREEN, " "))
		.append(TextSerializers.formattingCode('&').deserialize(message))
		.build();

	if (src instanceof Player && EssentialCmds.muteList.contains(((Player) src).getUniqueId()))
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You are muted!"));
		return;
	}

	MessageChannel.TO_ALL.send(finalMessage);
}
 
Example #6
Source File: StopExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	Optional<String> stopMessage = ctx.<String> getOne("reason");

	if (stopMessage.isPresent())
	{
		Sponge.getServer().shutdown(TextSerializers.FORMATTING_CODE.deserialize(stopMessage.get()));
	}
	else
	{
		Sponge.getServer().shutdown();
	}

	src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Stopped server."));
	return CommandResult.success();
}
 
Example #7
Source File: BroadcastExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	String message = ctx.<String> getOne("message").get();
	Text msg = TextSerializers.formattingCode('&').deserialize(message);
	Text broadcast = Text.of(TextColors.DARK_GRAY, "[", TextColors.DARK_RED, "Broadcast", TextColors.DARK_GRAY, "]", TextColors.GREEN, " ");
	Text finalBroadcast = Text.builder().append(broadcast).append(msg).build();

	if ((message.contains("https://")) || (message.contains("http://")))
	{
		Text urlBroadcast = Text.builder().append(broadcast).append(Utils.getURL(message)).build();
		MessageChannel.TO_ALL.send(urlBroadcast);
	}
	else
	{
		MessageChannel.TO_ALL.send(finalBroadcast);
	}
}
 
Example #8
Source File: Utils.java    From EssentialCmds with MIT License 6 votes vote down vote up
public static Text getJoinMsg(String name)
{
	ConfigurationNode valueNode = Configs.getConfig(mainConfig).getNode((Object[]) ("message.join").split("\\."));
	String message;

	if (valueNode.getValue() != null)
	{
		message = valueNode.getString();
	}
	else
	{
		Utils.setJoinMsg("&4Welcome");
		message = "&4Welcome";
	}

	if ((message.contains("https://")) || (message.contains("http://")))
	{
		return Utils.getURL(message);
	}

	return TextSerializers.FORMATTING_CODE.deserialize(message.replaceAll("@p", name));
}
 
Example #9
Source File: InfoCommand.java    From ChangeSkin with MIT License 6 votes vote down vote up
private void sendSkinDetails(UUID uuid, UserPreference preference) {
    Optional<Player> optPlayer = Sponge.getServer().getPlayer(uuid);
    if (optPlayer.isPresent()) {
        Player player = optPlayer.get();

        Optional<SkinModel> optSkin = preference.getTargetSkin();
        if (optSkin.isPresent()) {
            String template = plugin.getCore().getMessage("skin-info");
            String formatted = formatter.apply(template, optSkin.get());

            Text text = TextSerializers.LEGACY_FORMATTING_CODE.deserialize(formatted);
            player.sendMessage(text);
        } else {
            plugin.sendMessage(player, "skin-not-found");
        }
    }
}
 
Example #10
Source File: LoanPayCommand.java    From EconomyLite with MIT License 5 votes vote down vote up
private String getPrefix(double amnt, Currency cur) {
    Text label = cur.getPluralDisplayName();
    if (amnt == 1.0) {
        label = cur.getDisplayName();
    }
    return TextSerializers.FORMATTING_CODE.serialize(label);
}
 
Example #11
Source File: SpongePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendTitle(String head, String sub) { // Not supported
    Text headText = TextSerializers.LEGACY_FORMATTING_CODE.deserialize(BBC.color(head));
    Text subText = TextSerializers.LEGACY_FORMATTING_CODE.deserialize(BBC.color(sub));
    final Title title = Title.builder().title(headText).subtitle(subText).fadeIn(0).stay(60).fadeOut(20).build();
    parent.sendTitle(title);
}
 
Example #12
Source File: ChangeSkinSponge.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void sendMessage(CommandSource receiver, String key) {
    String message = core.getMessage(key);
    if (message != null && receiver != null) {
        receiver.sendMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(message));
    }
}
 
Example #13
Source File: LoanBalanceCommand.java    From EconomyLite with MIT License 5 votes vote down vote up
private String getPrefix(double amnt, Currency cur) {
    Text label = cur.getPluralDisplayName();
    if (amnt == 1.0) {
        label = cur.getDisplayName();
    }
    return TextSerializers.FORMATTING_CODE.serialize(label);
}
 
Example #14
Source File: LoreBase.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	String lore = ctx.<String> getOne("lore").get();

	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent())
		{
			ItemStack stack = player.getItemInHand(HandTypes.MAIN_HAND).get();
			LoreData loreData = stack.getOrCreate(LoreData.class).get();
			Text textLore = TextSerializers.FORMATTING_CODE.deserialize(lore);
			List<Text> newLore = loreData.lore().get();
			newLore.add(textLore);
			DataTransactionResult dataTransactionResult = stack.offer(Keys.ITEM_LORE, newLore);

			if (dataTransactionResult.isSuccessful())
			{
				player.setItemInHand(HandTypes.MAIN_HAND, stack);
				src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Added lore to item."));
			}
			else
			{
				src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Could not add lore to item."));
			}
		}
		else
		{
			src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be holding an item!"));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be a player to name items."));
	}
	return CommandResult.success();
}
 
Example #15
Source File: LoanTakeCommand.java    From EconomyLite with MIT License 5 votes vote down vote up
private String getPrefix(double amnt, Currency cur) {
    Text label = cur.getPluralDisplayName();
    if (amnt == 1.0) {
        label = cur.getDisplayName();
    }
    return TextSerializers.FORMATTING_CODE.serialize(label);
}
 
Example #16
Source File: LoanListener.java    From EconomyLite with MIT License 5 votes vote down vote up
private String getPrefix(double amnt, Currency cur) {
    Text label = cur.getPluralDisplayName();
    if (amnt == 1.0) {
        label = cur.getDisplayName();
    }
    return TextSerializers.FORMATTING_CODE.serialize(label);
}
 
Example #17
Source File: SpongePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendTitle(String head, String sub) { // Not supported
    Text headText = TextSerializers.LEGACY_FORMATTING_CODE.deserialize(BBC.color(head));
    Text subText = TextSerializers.LEGACY_FORMATTING_CODE.deserialize(BBC.color(sub));
    final Title title = Title.builder().title(headText).subtitle(subText).fadeIn(0).stay(60).fadeOut(20).build();
    parent.sendTitle(title);
}
 
Example #18
Source File: BanExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	Game game = EssentialCmds.getEssentialCmds().getGame();
	User player = ctx.<User> getOne("player").get();
	String reason = ctx.<String> getOne("reason").orElse("The BanHammer has spoken!");

	BanService srv = game.getServiceManager().provide(BanService.class).get();

	if (srv.isBanned(player.getProfile()))
	{
		src.sendMessage(Text.of(TextColors.RED, "That player has already been banned."));
		return CommandResult.empty();
	}
	
	srv.addBan(Ban.builder().type(BanTypes.PROFILE).source(src).profile(player.getProfile()).reason(TextSerializers.formattingCode('&').deserialize(reason)).build());

	if (player.isOnline())
	{
		player.getPlayer().get().kick(Text.builder()
			.append(Text.of(TextColors.DARK_RED, "You have been banned!\n ", TextColors.RED, "Reason: "))
			.append(TextSerializers.formattingCode('&').deserialize(reason))
			.build());
	}

	src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, player.getName() + " has been banned."));
	return CommandResult.success();
}
 
Example #19
Source File: SetNameExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	String name = ctx.<String> getOne("name").get();

	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent())
		{
			ItemStack stack = player.getItemInHand(HandTypes.MAIN_HAND).get();
			Text textName = TextSerializers.FORMATTING_CODE.deserialize(name);
			DataTransactionResult dataTransactionResult = stack.offer(Keys.DISPLAY_NAME, textName);
			
			if(dataTransactionResult.isSuccessful())
			{
				player.setItemInHand(HandTypes.MAIN_HAND, stack);
				src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Set name on item."));
			}
			else
			{
				src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Could not set name on item."));
			}
		}
		else
		{
			src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be holding an item!"));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be a player to name items."));
	}

	return CommandResult.success();
}
 
Example #20
Source File: VShopServlet.java    From Web-API with MIT License 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@POST
@Path("/shop")
@Permission({"vshop", "create"})
@ApiOperation(
        value = "Create Shops",
        notes = "Spawn a new shop with base values; Some values are only set by update",
        response = CachedVShop.class)
public Response createShop(CachedVShop req)
        throws URISyntaxException {

    if (req == null)
        throw new BadRequestException("Request body is required");

    CachedVShop shop = WebAPI.runOnMain(() -> {
        //Optional<EntityType> et = Sponge.getRegistry().getType(EntityType.class, req.getEntityType());
        EntityType et = req.getEntityType().getLive(EntityType.class).orElse(null);
        if (et == null)
            throw new BadRequestException("EntityType " + req.getEntityType() + " is unknown");
        String va = req.getEntityVariant();
        Optional<Location> location = req.getLocation().getLive();
        if (!location.isPresent())
            throw new BadRequestException("Could not get Live version of Location");

        NPCguard npc = API.create(et,
                va == null ? "none" : va,
                TextSerializers.FORMATTING_CODE.deserialize(req.getName()),
                location.get(),
                req.getRotation());
        VShopCompareUtils.applyDiv(req, npc);

        return new CachedVShop(npc);
    });

    return Response.created(new URI(null, null, shop.getLink(), null))
            .entity(shop).build();
}
 
Example #21
Source File: KickAllExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	String reason = ctx.<String> getOne("reason").get();
	Text reas = TextSerializers.formattingCode('&').deserialize(reason);

	for(Player player : Sponge.getServer().getOnlinePlayers())
	{
		if(!src.equals(player))
			player.kick(reas);
	}

	src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Kicked all players."));
	return CommandResult.success();
}
 
Example #22
Source File: KickExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	Game game = EssentialCmds.getEssentialCmds().getGame();
	Server server = game.getServer();
	Player player = ctx.<Player> getOne("player").get();
	Optional<String> reason = ctx.<String> getOne("reason");

	if (server.getPlayer(player.getUniqueId()).isPresent())
	{
		Text finalKickMessage = Text.of(TextColors.GOLD, src.getName() + " kicked " + player.getName());

		if (reason.isPresent())
		{
			Text reas = TextSerializers.formattingCode('&').deserialize(reason.get());
			Text kickMessage = Text.of(TextColors.GOLD, src.getName() + " kicked " + player.getName() + " for ", TextColors.RED);
			finalKickMessage = Text.builder().append(kickMessage).append(reas).build();
			player.kick(reas);
		}
		else
		{
			player.kick();
		}

		MessageChannel.TO_ALL.send(finalKickMessage);
		src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Player kicked."));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Player doesn't appear to be online!"));
	}

	return CommandResult.success();
}
 
Example #23
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Text getURL(String message)
{
	List<String> extractedUrls = extractUrls(message);
	for (String url : extractedUrls)
	{
		List<String> extractmb = extractmbefore(message);
		for (String preurl : extractmb)
		{
			List<String> extractma = extractmafter(message);
			for (String posturl : extractma)
			{
				try
				{
					String preurlline = preurl.replaceAll("(((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*).*?)(?=\\w).*", "");
					String posturlline = posturl.replaceAll("((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)", "");
					Text preMessage = TextSerializers.FORMATTING_CODE.deserialize(preurlline);
					Text postMessage = TextSerializers.FORMATTING_CODE.deserialize(posturlline);
					Text linkmessage = Text.builder(url).onClick(TextActions.openUrl(new URL(url))).build();
					Text newmessage = Text.builder().append(preMessage).append(linkmessage).append(postMessage).build();
					return newmessage;
				}
				catch (MalformedURLException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	return TextSerializers.FORMATTING_CODE.deserialize(message);
}
 
Example #24
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Text getLoginMessage(String playerName)
{
	CommentedConfigurationNode node = Configs.getConfig(mainConfig).getNode("message", "login");
	String message;

	if (configManager.getString(node).isPresent())
	{
		message = node.getString();
	}
	else
	{
		setLoginMessage("");
		message = "";
	}

	if (message.isEmpty())
	{
		return Text.EMPTY;
	}

	message = message.replaceAll("@p", playerName);

	if ((message.contains("https://")) || (message.contains("http://")))
	{
		return Utils.getURL(message);
	}

	return TextSerializers.FORMATTING_CODE.deserialize(message);
}
 
Example #25
Source File: CommandClaimGreeting.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Text result = claim.allowEdit(player);
    if (result != null) {
        GriefPreventionPlugin.sendMessage(src, result);
        return CommandResult.success();
    }

    final Text greeting = TextSerializers.FORMATTING_CODE.deserialize(ctx.<String>getOne("message").get());
    if (greeting.isEmpty()) {
        claim.getInternalClaimData().setGreeting(null);
    } else {
        claim.getInternalClaimData().setGreeting(greeting);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    final Text message = GriefPreventionPlugin.instance.messageData.claimGreeting
            .apply(ImmutableMap.of(
            "greeting", greeting)).build();
    GriefPreventionPlugin.sendMessage(src, message);

    return CommandResult.success();
}
 
Example #26
Source File: CommandTownTag.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    if (claim == null || !claim.isInTown()) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText());
        return CommandResult.empty();
    }

    final GPClaim town = claim.getTownClaim();
    final Text result = town.allowEdit(player);
    if (result != null) {
        GriefPreventionPlugin.sendMessage(src, result);
        return CommandResult.success();
    }

    Text name = TextSerializers.FORMATTING_CODE.deserialize(ctx.<String>getOne("tag").get());
    if (name.isEmpty()) {
        town.getTownData().setTownTag(null);
    } else {
        town.getTownData().setTownTag(name);
    }

    town.getInternalClaimData().setRequiresSave(true);
    final Text message = GriefPreventionPlugin.instance.messageData.townTag
            .apply(ImmutableMap.of(
            "tag", name)).build();
    GriefPreventionPlugin.sendMessage(src, message);
    return CommandResult.success();
}
 
Example #27
Source File: CommandClaimFarewell.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    if (claim != null) {
        if (claim.allowEdit(player) != null) {
            GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.permissionEditClaim.toText());
            return CommandResult.success();
        }

        Text farewell = TextSerializers.FORMATTING_CODE.deserialize(ctx.<String>getOne("message").get());
        if (farewell.isEmpty()) {
            claim.getInternalClaimData().setFarewell(null);
        } else {
            claim.getInternalClaimData().setFarewell(farewell);
        }
        claim.getInternalClaimData().setRequiresSave(true);
        final Text message = GriefPreventionPlugin.instance.messageData.claimFarewell
                .apply(ImmutableMap.of(
                "farewell", farewell)).build();
        GriefPreventionPlugin.sendMessage(src, message);
    } else {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.claimNotFound.toText());
    }

    return CommandResult.success();
}
 
Example #28
Source File: InteractiveMessageOption.java    From Web-API with MIT License 5 votes vote down vote up
/**
 * Gets the value of the message option that is displayed to the user.
 * @return The value of the message option.
 */
@ApiModelProperty(dataType = "string", value = "The value of the option (this is displayed to the player)", required = true)
@JsonIgnore
public Text getValue() {
    if (value == null) {
        return null;
    }
    return TextSerializers.FORMATTING_CODE.deserialize(value);
}
 
Example #29
Source File: InteractiveMessage.java    From Web-API with MIT License 5 votes vote down vote up
/**
 * The message that is sent.
 * @return The message content.
 */
@ApiModelProperty(dataType = "string", value = "The actual content of the message")
@JsonDetails
public Text getMessage() {
    if (message == null) {
        return null;
    }
    return TextSerializers.FORMATTING_CODE.deserialize(message);
}
 
Example #30
Source File: CommandClaimName.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext ctx) {
    Player player;
    try {
        player = GriefPreventionPlugin.checkPlayer(src);
    } catch (CommandException e) {
        src.sendMessage(e.getText());
        return CommandResult.success();
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GPClaim claim = GriefPreventionPlugin.instance.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Text result = claim.allowEdit(player);
    if (result != null) {
        GriefPreventionPlugin.sendMessage(player, result);
        return CommandResult.success();
    }

    final Text name = TextSerializers.FORMATTING_CODE.deserialize(ctx.<String>getOne("name").get());
    if (name.isEmpty()) {
        claim.getInternalClaimData().setName(null);
    } else {
        claim.getInternalClaimData().setName(name);
    }
    claim.getInternalClaimData().setRequiresSave(true);
    final Text message = GriefPreventionPlugin.instance.messageData.commandClaimName
            .apply(ImmutableMap.of(
            "name", name)).build();
    GriefPreventionPlugin.sendMessage(src, message);

    return CommandResult.success();
}