Search in sources :

Example 11 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project SpongeAPI by SpongePowered.

the class SpongeAbstractEventTest method testValueChangeEvent.

@Test
public void testValueChangeEvent() {
    DataTransactionResult original = DataTransactionResult.failNoData();
    DataTransactionResult modified = DataTransactionResult.successNoData();
    ChangeDataHolderEvent.ValueChange event = SpongeEventFactory.createChangeDataHolderEventValueChange(Cause.of(EventContext.empty(), "none"), original, mockParam(DataHolder.class));
    assertThat(event.getOriginalChanges(), is(equalTo(original)));
    event.proposeChanges(modified);
    assertThat(event.getEndResult(), is(equalTo(modified)));
}
Also used : DataHolder(org.spongepowered.api.data.DataHolder) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) ChangeDataHolderEvent(org.spongepowered.api.event.data.ChangeDataHolderEvent) Test(org.junit.Test)

Example 12 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project SpongeAPI by SpongePowered.

the class ItemStackBuilderPopulators method values.

/**
 * Creates a new {@link BiConsumer} that applies a random selection of the
 * provided {@link BaseValue}s.
 *
 * <p>Note that custom data is not supported through this method, use
 * {@link #data(Collection)} or any variant thereof for applying custom data.</p>
 *
 * @param values The iterable collection of values to choose from
 * @param <E> The type of element
 * @param <V> The type of value
 * @return The new biconsumer to apply to an itemstack builder
 */
public static <E, V extends BaseValue<E>> BiConsumer<ItemStack.Builder, Random> values(Iterable<V> values) {
    WeightedTable<V> tableEntries = new WeightedTable<>(1);
    for (V value : values) {
        tableEntries.add(checkNotNull(value, "Value cannot be null!"), 1);
    }
    return ((builder, random) -> {
        final V value = tableEntries.get(random).get(0);
        final ItemStack itemStack = builder.build();
        final DataTransactionResult result = itemStack.offer(value);
        if (result.isSuccessful()) {
            builder.from(itemStack);
        }
    });
}
Also used : WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Example 13 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project SpongeForge by SpongePowered.

the class MixinFluidStack method offer.

@Override
public DataTransactionResult offer(Iterable<DataManipulator<?, ?>> valueContainers) {
    DataTransactionResult.Builder builder = DataTransactionResult.builder();
    for (DataManipulator<?, ?> manipulator : valueContainers) {
        final DataTransactionResult result = offer(manipulator);
        if (!result.getRejectedData().isEmpty()) {
            builder.reject(result.getRejectedData());
        }
        if (!result.getReplacedData().isEmpty()) {
            builder.replace(result.getReplacedData());
        }
        if (!result.getSuccessfulData().isEmpty()) {
            builder.success(result.getSuccessfulData());
        }
        final DataTransactionResult.Type type = result.getType();
        builder.result(type);
        switch(type) {
            case UNDEFINED:
            case ERROR:
            case CANCELLED:
                return builder.build();
            default:
                break;
        }
    }
    return builder.build();
}
Also used : DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Example 14 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project Nucleus by NucleusPowered.

the class GamemodeBase method baseCommand.

CommandResult baseCommand(CommandSource src, Player user, GameMode gm) throws Exception {
    if (!this.permissions.testSuffix(src, MODE_MAP.computeIfAbsent(gm.getId(), key -> {
        String[] keySplit = key.split(":", 2);
        String r = keySplit[keySplit.length - 1].toLowerCase();
        MODE_MAP.put(key, "modes." + r);
        return "modes." + r;
    }))) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.gamemode.permission", gm.getTranslation().get()));
    }
    DataTransactionResult dtr = user.offer(Keys.GAME_MODE, gm);
    if (dtr.isSuccessful()) {
        if (!src.equals(user)) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.gamemode.set.other", user.getName(), gm.getName()));
        }
        user.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.gamemode.set.base", gm.getName()));
        return CommandResult.success();
    }
    throw ReturnMessageException.fromKey("command.gamemode.error", user.getName());
}
Also used : DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException)

Example 15 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project Nucleus by NucleusPowered.

the class EnchantCommand method executeCommand.

@Override
public CommandResult executeCommand(Player src, CommandContext args) throws Exception {
    // Check for item in hand
    if (!src.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.noitem"));
        return CommandResult.empty();
    }
    // Get the arguments
    ItemStack itemInHand = src.getItemInHand(HandTypes.MAIN_HAND).get();
    EnchantmentType enchantment = args.<EnchantmentType>getOne(enchantmentKey).get();
    int level = args.<Integer>getOne(levelKey).get();
    boolean allowUnsafe = args.hasAny("u");
    boolean allowOverwrite = args.hasAny("o");
    // Can we apply the enchantment?
    if (!allowUnsafe) {
        if (!enchantment.canBeAppliedToStack(itemInHand)) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.enchant", itemInHand.getTranslation().get()));
            return CommandResult.empty();
        }
        if (level > enchantment.getMaximumLevel()) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.level", itemInHand.getTranslation().get()));
            return CommandResult.empty();
        }
    }
    // We know this should exist.
    EnchantmentData ed = itemInHand.getOrCreate(EnchantmentData.class).get();
    // Get all the enchantments.
    List<Enchantment> currentEnchants = ed.getListValue().get();
    List<Enchantment> enchantmentsToRemove = currentEnchants.stream().filter(x -> !x.getType().isCompatibleWith(enchantment) || x.getType().equals(enchantment)).collect(Collectors.toList());
    if (!allowOverwrite && !enchantmentsToRemove.isEmpty()) {
        // Build the list of the enchantment names, and send it.
        final StringBuilder sb = new StringBuilder();
        enchantmentsToRemove.forEach(x -> {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(Util.getTranslatableIfPresent(x.getType()));
        });
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.overwrite", sb.toString()));
        return CommandResult.empty();
    }
    // Remove all enchants that cannot co-exist.
    currentEnchants.removeIf(enchantmentsToRemove::contains);
    // Create the enchantment
    currentEnchants.add(Enchantment.of(enchantment, level));
    ed.setElements(currentEnchants);
    // Offer it to the item.
    DataTransactionResult dtr = itemInHand.offer(ed);
    if (dtr.isSuccessful()) {
        // If successful, we need to put the item in the player's hand for it to actually take effect.
        src.setItemInHand(HandTypes.MAIN_HAND, itemInHand);
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.success", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
        return CommandResult.success();
    }
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.error", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
    return CommandResult.empty();
}
Also used : RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) GenericArguments(org.spongepowered.api.command.args.GenericArguments) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) Enchantment(org.spongepowered.api.item.enchantment.Enchantment) ItemStack(org.spongepowered.api.item.inventory.ItemStack) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Map(java.util.Map) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Util(io.github.nucleuspowered.nucleus.Util) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) ImprovedCatalogTypeArgument(io.github.nucleuspowered.nucleus.argumentparsers.ImprovedCatalogTypeArgument) BoundedIntegerArgument(io.github.nucleuspowered.nucleus.argumentparsers.BoundedIntegerArgument) CommandResult(org.spongepowered.api.command.CommandResult) Maps(com.google.common.collect.Maps) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) EnchantmentData(org.spongepowered.api.data.manipulator.mutable.item.EnchantmentData) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) HandTypes(org.spongepowered.api.data.type.HandTypes) EssentialsEquivalent(io.github.nucleuspowered.nucleus.internal.docgen.annotations.EssentialsEquivalent) Player(org.spongepowered.api.entity.living.player.Player) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) ItemStack(org.spongepowered.api.item.inventory.ItemStack) EnchantmentData(org.spongepowered.api.data.manipulator.mutable.item.EnchantmentData) Enchantment(org.spongepowered.api.item.enchantment.Enchantment)

Aggregations

DataTransactionResult (org.spongepowered.api.data.DataTransactionResult)29 ItemStack (org.spongepowered.api.item.inventory.ItemStack)6 DataHolder (org.spongepowered.api.data.DataHolder)4 ImmutableValue (org.spongepowered.api.data.value.immutable.ImmutableValue)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 BlockState (org.spongepowered.api.block.BlockState)3 BaseValue (org.spongepowered.api.data.value.BaseValue)3 Player (org.spongepowered.api.entity.living.player.Player)3 IMixinCustomDataHolder (org.spongepowered.common.interfaces.data.IMixinCustomDataHolder)3 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 Set (java.util.Set)2 EnumFacing (net.minecraft.util.EnumFacing)2 Sponge (org.spongepowered.api.Sponge)2 TileEntity (org.spongepowered.api.block.tileentity.TileEntity)2 DataView (org.spongepowered.api.data.DataView)2