Search in sources :

Example 11 with ListItem

use of com.almuradev.almura.feature.exchange.listing.ListItem in project Almura by AlmuraDev.

the class ServerExchangeManager method loadListItems.

/**
 * ListItem
 */
private void loadListItems(final Exchange axs) {
    checkNotNull(axs);
    this.logger.info("Querying list items for exchange '{}' ({}), please wait...", axs.getName(), axs.getId());
    final List<ListItem> items = new ArrayList<>();
    try (final DSLContext context = this.databaseManager.createContext(true)) {
        final Results results = ExchangeQueries.createFetchListItemsAndDataFor(axs.getId(), false).build(context).keepStatement(false).fetchMany();
        results.forEach(result -> items.addAll(this.parseListItemsFrom(result)));
        axs.clearListItems();
        axs.clearForSaleItems();
        final Map<UUID, List<ListItem>> itemsByOwner = items.stream().collect(Collectors.groupingBy(ListItem::getSeller));
        itemsByOwner.forEach((key, value) -> value.sort(Comparator.comparingInt(ListItem::getIndex)));
        axs.putListItems(itemsByOwner.isEmpty() ? null : itemsByOwner);
        this.logger.info("Loaded [{}] list item(s) for exchange '{}' ({}).", items.size(), axs.getName(), axs.getId());
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Also used : Results(org.jooq.Results) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) DSLContext(org.jooq.DSLContext) List(java.util.List) ArrayList(java.util.ArrayList) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) UUID(java.util.UUID)

Example 12 with ListItem

use of com.almuradev.almura.feature.exchange.listing.ListItem in project Almura by AlmuraDev.

the class ServerExchangeManager method handleForSaleFilter.

public void handleForSaleFilter(final Player player, final String id, @Nullable final String filter, @Nullable final String sorter, final int skip, final int limit) {
    checkNotNull(player);
    checkNotNull(id);
    checkState(skip >= 0);
    final Exchange axs = this.getExchange(id).orElse(null);
    if (axs == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the " + "server console for more details!"));
        this.logger.error("Player '{}' attempted to filter for sale items for exchange '{}' but the server has no knowledge of it. Syncing " + "exchange registry...", player.getName(), id);
        this.syncExchangeRegistryTo(player);
        return;
    }
    Stream<ForSaleItem> stream = axs.getForSaleItems().values().stream().flatMap(List::stream);
    if (filter != null) {
        final List<FilterRegistry.FilterElement<ListItem>> elements = FilterRegistry.instance.getFilterElements(filter);
        stream = stream.filter(forSaleItem -> elements.stream().allMatch(element -> element.getFilter().test(forSaleItem.getListItem(), element.getValue())));
    }
    if (sorter != null) {
        final List<FilterRegistry.SorterElement<ListItem>> elements = FilterRegistry.instance.getSortingElements(sorter);
        final Comparator<ListItem> comparator = FilterRegistry.instance.buildSortingComparator(elements).orElse(null);
        if (comparator != null) {
            stream = stream.map(ForSaleItem::getListItem).sorted(comparator).map(k -> k.getForSaleItem().orElse(null));
        }
    }
    final List<ForSaleItem> result = stream.collect(Collectors.toList());
    final Stream<ForSaleItem> adjustedStream = result.stream().skip(skip);
    final List<ForSaleItem> limitedResult;
    if (limit > -1) {
        limitedResult = adjustedStream.limit(limit).collect(Collectors.toList());
    } else {
        limitedResult = adjustedStream.collect(Collectors.toList());
    }
    this.network.sendTo(player, new ClientboundForSaleItemsResponsePacket(axs.getId(), limitedResult, result.size()));
}
Also used : AxsListItemRecord(com.almuradev.generated.axs.tables.records.AxsListItemRecord) AxsListItemData(com.almuradev.generated.axs.tables.AxsListItemData) IItemHandler(net.minecraftforge.items.IItemHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) Results(org.jooq.Results) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) Item(net.minecraft.item.Item) Axs(com.almuradev.generated.axs.tables.Axs) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) DatabaseManager(com.almuradev.almura.shared.database.DatabaseManager) BigDecimal(java.math.BigDecimal) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) Map(java.util.Map) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) DSLContext(org.jooq.DSLContext) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ClientboundExchangeGuiResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeGuiResponsePacket) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) EconomyService(org.spongepowered.api.service.economy.EconomyService) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) Timestamp(java.sql.Timestamp) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) Sponge(org.spongepowered.api.Sponge) DatabaseQueue(com.almuradev.almura.shared.database.DatabaseQueue) ServiceManager(org.spongepowered.api.service.ServiceManager) NetworkConfig(com.almuradev.almura.shared.network.NetworkConfig) UUID(java.util.UUID) Result(org.jooq.Result) Instant(java.time.Instant) ClientboundExchangeRegistryPacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeRegistryPacket) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) ChannelBinding(org.spongepowered.api.network.ChannelBinding) List(java.util.List) Stream(java.util.stream.Stream) ExchangeQueries(com.almuradev.almura.feature.exchange.database.ExchangeQueries) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) ChannelId(org.spongepowered.api.network.ChannelId) IngameFeature(com.almuradev.almura.shared.feature.IngameFeature) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Almura(com.almuradev.almura.Almura) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) Getter(org.spongepowered.api.event.filter.Getter) GameStartingServerEvent(org.spongepowered.api.event.game.state.GameStartingServerEvent) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ArrayList(java.util.ArrayList) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) Inject(javax.inject.Inject) AxsListItemDataRecord(com.almuradev.generated.axs.tables.records.AxsListItemDataRecord) ItemStack(net.minecraft.item.ItemStack) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Text(org.spongepowered.api.text.Text) AxsForSaleItemRecord(com.almuradev.generated.axs.tables.records.AxsForSaleItemRecord) GameState(org.spongepowered.api.GameState) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) Record(org.jooq.Record) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ClientboundTransactionCompletePacket(com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Scheduler(org.spongepowered.api.scheduler.Scheduler) ServerNotificationManager(com.almuradev.almura.feature.notification.ServerNotificationManager) EnumFacing(net.minecraft.util.EnumFacing) IOException(java.io.IOException) SerializationUtil(com.almuradev.almura.shared.util.SerializationUtil) Witness(com.almuradev.core.event.Witness) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) ResourceLocation(net.minecraft.util.ResourceLocation) Listener(org.spongepowered.api.event.Listener) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Comparator(java.util.Comparator) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) List(java.util.List) ArrayList(java.util.ArrayList) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem)

Example 13 with ListItem

use of com.almuradev.almura.feature.exchange.listing.ListItem in project Almura by AlmuraDev.

the class ServerExchangeManager method loadForSaleItems.

/**
 * ForSaleItem
 */
private void loadForSaleItems(final Exchange axs) {
    checkNotNull(axs);
    this.logger.info("Querying for sale items for exchange '{}' ({}), please wait...", axs.getName(), axs.getId());
    final List<ForSaleItem> forSaleItems = new ArrayList<>();
    final List<ListItem> listItems = axs.getListItems().entrySet().stream().map(Map.Entry::getValue).flatMap(List::stream).collect(Collectors.toList());
    try (final DSLContext context = this.databaseManager.createContext(true)) {
        final Results results = ExchangeQueries.createFetchForSaleItemsFor(axs.getId(), false).build(context).keepStatement(false).fetchMany();
        results.forEach(result -> forSaleItems.addAll(this.parseForSaleItemsFrom(listItems, result)));
        axs.clearForSaleItems();
        axs.putForSaleItems(forSaleItems.isEmpty() ? null : forSaleItems.stream().collect(Collectors.groupingBy(forSaleItem -> forSaleItem.getListItem().getSeller())));
        this.logger.info("Loaded [{}] for sale item(s) for exchange '{}' ({}).", forSaleItems.size(), axs.getName(), axs.getId());
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Also used : AxsListItemRecord(com.almuradev.generated.axs.tables.records.AxsListItemRecord) AxsListItemData(com.almuradev.generated.axs.tables.AxsListItemData) IItemHandler(net.minecraftforge.items.IItemHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) Results(org.jooq.Results) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) Item(net.minecraft.item.Item) Axs(com.almuradev.generated.axs.tables.Axs) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) DatabaseManager(com.almuradev.almura.shared.database.DatabaseManager) BigDecimal(java.math.BigDecimal) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) Map(java.util.Map) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) DSLContext(org.jooq.DSLContext) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ClientboundExchangeGuiResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeGuiResponsePacket) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) EconomyService(org.spongepowered.api.service.economy.EconomyService) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) Timestamp(java.sql.Timestamp) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) Sponge(org.spongepowered.api.Sponge) DatabaseQueue(com.almuradev.almura.shared.database.DatabaseQueue) ServiceManager(org.spongepowered.api.service.ServiceManager) NetworkConfig(com.almuradev.almura.shared.network.NetworkConfig) UUID(java.util.UUID) Result(org.jooq.Result) Instant(java.time.Instant) ClientboundExchangeRegistryPacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeRegistryPacket) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) ChannelBinding(org.spongepowered.api.network.ChannelBinding) List(java.util.List) Stream(java.util.stream.Stream) ExchangeQueries(com.almuradev.almura.feature.exchange.database.ExchangeQueries) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) ChannelId(org.spongepowered.api.network.ChannelId) IngameFeature(com.almuradev.almura.shared.feature.IngameFeature) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Almura(com.almuradev.almura.Almura) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) Getter(org.spongepowered.api.event.filter.Getter) GameStartingServerEvent(org.spongepowered.api.event.game.state.GameStartingServerEvent) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ArrayList(java.util.ArrayList) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) Inject(javax.inject.Inject) AxsListItemDataRecord(com.almuradev.generated.axs.tables.records.AxsListItemDataRecord) ItemStack(net.minecraft.item.ItemStack) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Text(org.spongepowered.api.text.Text) AxsForSaleItemRecord(com.almuradev.generated.axs.tables.records.AxsForSaleItemRecord) GameState(org.spongepowered.api.GameState) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) Record(org.jooq.Record) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ClientboundTransactionCompletePacket(com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Scheduler(org.spongepowered.api.scheduler.Scheduler) ServerNotificationManager(com.almuradev.almura.feature.notification.ServerNotificationManager) EnumFacing(net.minecraft.util.EnumFacing) IOException(java.io.IOException) SerializationUtil(com.almuradev.almura.shared.util.SerializationUtil) Witness(com.almuradev.core.event.Witness) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) ResourceLocation(net.minecraft.util.ResourceLocation) Listener(org.spongepowered.api.event.Listener) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Comparator(java.util.Comparator) Results(org.jooq.Results) SQLException(java.sql.SQLException) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ArrayList(java.util.ArrayList) DSLContext(org.jooq.DSLContext) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem)

Example 14 with ListItem

use of com.almuradev.almura.feature.exchange.listing.ListItem in project Almura by AlmuraDev.

the class ServerExchangeManager method handleTransaction.

/**
 * Transaction
 */
public void handleTransaction(final Player player, final String id, final int listItemRecNo, final int quantity) {
    checkNotNull(player);
    checkNotNull(id);
    checkState(listItemRecNo >= 0);
    checkState(quantity > 0);
    final Exchange axs = this.getExchange(id).orElse(null);
    if (axs == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the " + "server console for more details!"));
        this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' but the server has no knowledge of it. Syncing exchange " + "registry...", player.getName(), id);
        this.syncExchangeRegistryTo(player);
        return;
    }
    final EconomyService economyService = this.serviceManager.provide(EconomyService.class).orElse(null);
    if (economyService == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the " + "server console for more details!"));
        this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' but the economy service no longer exists. This is a " + "critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
        return;
    }
    final UniqueAccount buyerAccount = economyService.getOrCreateAccount(player.getUniqueId()).orElse(null);
    if (buyerAccount == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the " + "server console for more details!"));
        this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' but the economy service returned no account for them. " + "This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
        return;
    }
    ListItem found = null;
    for (final Map.Entry<UUID, List<ListItem>> kv : axs.getListItems().entrySet()) {
        final ListItem listItem = kv.getValue().stream().filter(item -> item.getRecord() == listItemRecNo).findAny().orElse(null);
        if (listItem != null) {
            found = listItem;
            break;
        }
    }
    if (found == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("This item is no longer for sale!"));
        this.network.sendTo(player, new ClientboundForSaleFilterRequestPacket(axs.getId()));
        return;
    }
    final UUID seller = found.getSeller();
    final UUID buyer = player.getUniqueId();
    if (buyer.equals(seller)) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("You cannot purchase your own items."));
        return;
    }
    final UniqueAccount sellerAccount = economyService.getOrCreateAccount(seller).orElse(null);
    if (sellerAccount == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the " + "server console for more details!"));
        this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' but the economy service returned no account for seller" + " '{}'. This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id, seller);
        return;
    }
    final ForSaleItem forSaleItem = found.getForSaleItem().orElse(null);
    if (forSaleItem == null) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("This item is no longer for sale!"));
        this.network.sendTo(player, new ClientboundForSaleFilterRequestPacket(axs.getId()));
        return;
    }
    if (found.getQuantity() < quantity) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("There is not enough quantity left to " + "purchase this item!"));
        this.network.sendTo(player, new ClientboundForSaleFilterRequestPacket(axs.getId()));
        return;
    }
    final BigDecimal balance = buyerAccount.getBalance(economyService.getDefaultCurrency());
    final BigDecimal price = forSaleItem.getPrice();
    final double total = price.doubleValue() * quantity;
    if (total > balance.doubleValue()) {
        final String formattedTotal = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total);
        final String formattedBalance = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(balance.doubleValue());
        final String formattedDifference = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total - balance.doubleValue());
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("You attempted to purchase items totaling to ", TextColors.RED, formattedTotal, TextColors.RESET, " while you only have ", TextColors.GREEN, formattedBalance, TextColors.RESET, ".", Text.NEW_LINE, Text.NEW_LINE, "You need ", TextColors.LIGHT_PURPLE, formattedDifference, TextColors.RESET, " more!"));
        return;
    }
    EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
    final IItemHandler inventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
    final ListItem copyStack = found.copy();
    copyStack.setQuantity(quantity);
    final ItemStack simulatedResultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), true);
    if (!simulatedResultStack.isEmpty()) {
        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("You lack sufficient inventory space to " + "purchase these item(s)!"));
        return;
    }
    final int originalQuantity = found.getQuantity();
    final int quantityRemaining = originalQuantity - (quantity - simulatedResultStack.getCount());
    final int forSaleItemRecord = forSaleItem.getRecord();
    // Charge the buyer
    try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        frame.pushCause(axs);
        buyerAccount.transfer(sellerAccount, economyService.getDefaultCurrency(), BigDecimal.valueOf(total), frame.getCurrentCause());
    }
    this.scheduler.createTaskBuilder().async().execute(() -> {
        try (final DSLContext context = this.databaseManager.createContext(true)) {
            // Update listed quantity
            int result = ExchangeQueries.createUpdateListItemQuantity(listItemRecNo, quantityRemaining, true).build(context).execute();
            if (result == 0) {
                this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' to the database but it failed. Discarding " + "changes...", player.getName(), id);
                return;
            }
            if (quantityRemaining == 0) {
                result = ExchangeQueries.createUpdateForSaleItemIsHidden(forSaleItemRecord, true).build(context).execute();
                if (result == 0) {
                    this.logger.error("Player '{}' attempted to make a transaction in-which was the entire listing for exchange '{}' to the " + "database but it failed. Discarding changes...", player.getName(), id);
                    ExchangeQueries.createUpdateListItemQuantity(listItemRecNo, originalQuantity, true).build(context).execute();
                    return;
                }
            }
            // Issue a transaction
            result = ExchangeQueries.createInsertTransaction(Instant.now(), forSaleItemRecord, buyer, price, quantity).build(context).execute();
            if (result == 0) {
                this.logger.error("Player '{}' attempted to make a transaction for exchange '{}' to the database but it failed. Discarding " + "changes...", player.getName(), id);
                ExchangeQueries.createUpdateListItemQuantity(listItemRecNo, originalQuantity, false).build(context).execute();
                ExchangeQueries.createUpdateForSaleItemIsHidden(forSaleItemRecord, false).build(context).execute();
                return;
            }
            final Results listItemResults = ExchangeQueries.createFetchListItemsAndDataFor(seller, false).build(context).keepStatement(false).fetchMany();
            final Results forSaleItemResults = ExchangeQueries.createFetchForSaleItemsFor(seller, false).build(context).keepStatement(false).fetchMany();
            this.scheduler.createTaskBuilder().execute(() -> {
                final List<ListItem> listItems = new ArrayList<>();
                listItemResults.forEach(r -> listItems.addAll(this.parseListItemsFrom(r)));
                final List<ForSaleItem> forSaleItems = new ArrayList<>();
                forSaleItemResults.forEach(r -> forSaleItems.addAll(this.parseForSaleItemsFrom(listItems, r)));
                axs.putListItemsFor(seller, listItems);
                axs.putForSaleItemsFor(seller, forSaleItems);
                final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), false);
                if (!resultStack.isEmpty()) {
                // TODO Inventory changed awaiting DB and now we're full...could drop it on the ground? It is an off-case
                }
                // If the seller is online, send them a list item update
                final Player sellerPlayer = Sponge.getServer().getPlayer(seller).orElse(null);
                if (sellerPlayer != null) {
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsResponsePacket(axs.getId(), listItems));
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsSaleStatusPacket(axs.getId(), forSaleItems, null));
                }
                this.network.sendToAll(new ClientboundForSaleFilterRequestPacket(axs.getId()));
                Sponge.getServer().getPlayer(buyer).ifPresent(buyerPlayer -> this.network.sendTo(buyerPlayer, new ClientboundTransactionCompletePacket()));
            }).submit(this.container);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }).submit(this.container);
}
Also used : UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) EconomyService(org.spongepowered.api.service.economy.EconomyService) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) CauseStackManager(org.spongepowered.api.event.CauseStackManager) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) List(java.util.List) ArrayList(java.util.ArrayList) UUID(java.util.UUID) ClientboundTransactionCompletePacket(com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket) Player(org.spongepowered.api.entity.living.player.Player) IItemHandler(net.minecraftforge.items.IItemHandler) DSLContext(org.jooq.DSLContext) BigDecimal(java.math.BigDecimal) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) Results(org.jooq.Results) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) AxsListItem(com.almuradev.generated.axs.tables.AxsListItem) BasicListItem(com.almuradev.almura.feature.exchange.basic.listing.BasicListItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ItemStack(net.minecraft.item.ItemStack) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with ListItem

use of com.almuradev.almura.feature.exchange.listing.ListItem in project Almura by AlmuraDev.

the class ExchangeModule method configure.

@Override
protected void configure() {
    this.requestStaticInjection(ExchangeCommandsCreator.class);
    this.packet().bind(ClientboundExchangeRegistryPacket.class, binder -> binder.handler(ClientboundExchangesRegistryPacketHandler.class, Platform.Type.CLIENT)).bind(ServerboundExchangeSpecificOfferRequestPacket.class, binder -> binder.handler(ServerboundExchangeSpecificOfferPacketHandler.class, Platform.Type.SERVER)).bind(ClientboundExchangeGuiResponsePacket.class, binder -> binder.handler(ClientboundExchangeGuiResponsePacketHandler.class, Platform.Type.CLIENT)).bind(ServerboundModifyExchangePacket.class, binder -> binder.handler(ServerboundModifyExchangePacketHandler.class, Platform.Type.SERVER)).bind(ClientboundListItemsResponsePacket.class, binder -> binder.handler(ClientboundListItemsResponsePacketHandler.class, Platform.Type.CLIENT)).bind(ClientboundListItemsSaleStatusPacket.class, binder -> binder.handler(ClientboundListItemsSaleStatusPacketHandler.class, Platform.Type.CLIENT)).bind(ServerboundListItemsRequestPacket.class, binder -> binder.handler(ServerboundListItemsRequestPacketHandler.class, Platform.Type.SERVER)).bind(ClientboundForSaleFilterRequestPacket.class, binder -> binder.handler(ClientboundForSaleFilterRequestPacketHandler.class, Platform.Type.CLIENT)).bind(ServerboundForSaleFilterResponsePacket.class, binder -> binder.handler(ServerboundForSaleFilterResponsePacketHandler.class, Platform.Type.SERVER)).bind(ClientboundForSaleItemsResponsePacket.class, binder -> binder.handler(ClientboundForSaleItemsResponsePacketHandler.class, Platform.Type.CLIENT)).bind(ServerboundModifyForSaleItemListStatusRequestPacket.class, binder -> binder.handler(ServerboundModifyForSaleItemListStatusRequestPacketHandler.class, Platform.Type.SERVER)).bind(ServerboundTransactionRequestPacket.class, binder -> binder.handler(ServerboundTransactionRequestPacketHandler.class, Platform.Type.SERVER)).bind(ClientboundTransactionCompletePacket.class, binder -> binder.handler(ClientboundTransactionCompletePacketHandler.class, Platform.Type.CLIENT));
    this.facet().add(ServerExchangeManager.class);
    this.command().child(ExchangeCommandsCreator.createCommand(), "exchange", "axs");
    FilterRegistry.instance.<ListItem>registerFilter(ID + "_item_display_name", (target, value) -> target.asRealStack().getDisplayName().toLowerCase().contains(value.toLowerCase())).<ListItem>registerFilter(ID + "_seller_name", (target, value) -> target.getSellerName().isPresent() && target.getSellerName().get().toLowerCase().contains(value.toLowerCase())).<ListItem>registerComparator(ID + "_item_display_name", Comparator.comparing(k -> k.asRealStack().getDisplayName().toLowerCase())).<ListItem>registerComparator(ID + "_seller_name", Comparator.comparing(v -> v.getSellerName().orElse("").toLowerCase())).<ListItem>registerComparator(ID + "_price", Comparator.comparing(l -> {
        final ForSaleItem item = l.getForSaleItem().orElse(null);
        if (item == null) {
            return null;
        }
        return item.getPrice();
    })).<ListItem>registerComparator(ID + "_created", Comparator.comparing(l -> {
        final ForSaleItem item = l.getForSaleItem().orElse(null);
        if (item == null) {
            return null;
        }
        return item.getCreated();
    }));
    this.on(Platform.Type.CLIENT, () -> {
        @SideOnly(Side.CLIENT)
        final class ClientModule extends AbstractModule implements ClientBinder {

            @SideOnly(Side.CLIENT)
            @Override
            protected void configure() {
                this.facet().add(ClientExchangeManager.class);
                this.requestStaticInjection(ExchangeBuyQuantityScreen.class);
                this.requestStaticInjection(ExchangeListPriceScreen.class);
                this.requestStaticInjection(ExchangeOfferScreen.class);
                this.requestStaticInjection(ExchangeManagementScreen.class);
                this.requestStaticInjection(ExchangeScreen.class);
            }
        }
        this.install(new ClientModule());
    });
}
Also used : ServerboundTransactionRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundTransactionRequestPacketHandler) ServerboundListItemsRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundListItemsRequestPacketHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) ServerboundTransactionRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundTransactionRequestPacket) ServerboundModifyForSaleItemListStatusRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundModifyForSaleItemListStatusRequestPacket) ServerboundModifyExchangePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundModifyExchangePacketHandler) ServerboundExchangeSpecificOfferPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundExchangeSpecificOfferPacketHandler) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) Platform(org.spongepowered.api.Platform) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) ClientboundForSaleFilterRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundForSaleFilterRequestPacketHandler) ExchangeBuyQuantityScreen(com.almuradev.almura.feature.exchange.client.gui.ExchangeBuyQuantityScreen) ServerboundForSaleFilterResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundForSaleFilterResponsePacketHandler) Side(net.minecraftforge.fml.relauncher.Side) ServerboundModifyExchangePacket(com.almuradev.almura.feature.exchange.network.ServerboundModifyExchangePacket) ExchangeOfferScreen(com.almuradev.almura.feature.exchange.client.gui.ExchangeOfferScreen) ClientboundTransactionCompletePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundTransactionCompletePacketHandler) ExchangeScreen(com.almuradev.almura.feature.exchange.client.gui.ExchangeScreen) ClientboundExchangeGuiResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeGuiResponsePacket) ClientBinder(com.almuradev.almura.shared.inject.ClientBinder) SideOnly(net.minecraftforge.fml.relauncher.SideOnly) ExchangeListPriceScreen(com.almuradev.almura.feature.exchange.client.gui.ExchangeListPriceScreen) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) ClientboundExchangesRegistryPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundExchangesRegistryPacketHandler) ExchangeManagementScreen(com.almuradev.almura.feature.exchange.client.gui.ExchangeManagementScreen) ClientExchangeManager(com.almuradev.almura.feature.exchange.client.ClientExchangeManager) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) CommonBinder(com.almuradev.almura.shared.inject.CommonBinder) ServerboundListItemsRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundListItemsRequestPacket) ClientboundTransactionCompletePacket(com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket) ServerboundForSaleFilterResponsePacket(com.almuradev.almura.feature.exchange.network.ServerboundForSaleFilterResponsePacket) ClientboundListItemsResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundListItemsResponsePacketHandler) AbstractModule(net.kyori.violet.AbstractModule) ClientboundExchangeRegistryPacket(com.almuradev.almura.feature.exchange.network.ClientboundExchangeRegistryPacket) ClientboundExchangeGuiResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundExchangeGuiResponsePacketHandler) ClientboundForSaleItemsResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundForSaleItemsResponsePacketHandler) ServerboundModifyForSaleItemListStatusRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundModifyForSaleItemListStatusRequestPacketHandler) ServerboundExchangeSpecificOfferRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundExchangeSpecificOfferRequestPacket) Comparator(java.util.Comparator) ClientboundListItemsSaleStatusPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundListItemsSaleStatusPacketHandler) ClientboundTransactionCompletePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundTransactionCompletePacketHandler) ServerboundListItemsRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundListItemsRequestPacketHandler) ClientboundExchangesRegistryPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundExchangesRegistryPacketHandler) SideOnly(net.minecraftforge.fml.relauncher.SideOnly) ClientboundForSaleItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleItemsResponsePacket) ServerboundTransactionRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundTransactionRequestPacket) ClientboundExchangeGuiResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundExchangeGuiResponsePacketHandler) AbstractModule(net.kyori.violet.AbstractModule) ServerboundForSaleFilterResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundForSaleFilterResponsePacketHandler) ServerboundExchangeSpecificOfferRequestPacket(com.almuradev.almura.feature.exchange.network.ServerboundExchangeSpecificOfferRequestPacket) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) ServerboundModifyForSaleItemListStatusRequestPacketHandler(com.almuradev.almura.feature.exchange.network.handler.ServerboundModifyForSaleItemListStatusRequestPacketHandler) ClientboundForSaleFilterRequestPacket(com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) ListItem(com.almuradev.almura.feature.exchange.listing.ListItem) ClientboundListItemsResponsePacketHandler(com.almuradev.almura.feature.exchange.network.handler.ClientboundListItemsResponsePacketHandler) ClientBinder(com.almuradev.almura.shared.inject.ClientBinder) ServerboundModifyExchangePacket(com.almuradev.almura.feature.exchange.network.ServerboundModifyExchangePacket)

Aggregations

ListItem (com.almuradev.almura.feature.exchange.listing.ListItem)17 BasicListItem (com.almuradev.almura.feature.exchange.basic.listing.BasicListItem)14 ForSaleItem (com.almuradev.almura.feature.exchange.listing.ForSaleItem)14 BasicForSaleItem (com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem)12 AxsListItem (com.almuradev.generated.axs.tables.AxsListItem)11 ClientboundListItemsSaleStatusPacket (com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket)10 AxsForSaleItem (com.almuradev.generated.axs.tables.AxsForSaleItem)10 ClientboundForSaleFilterRequestPacket (com.almuradev.almura.feature.exchange.network.ClientboundForSaleFilterRequestPacket)9 ClientboundListItemsResponsePacket (com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket)9 SQLException (java.sql.SQLException)8 ArrayList (java.util.ArrayList)8 DSLContext (org.jooq.DSLContext)8 BasicExchange (com.almuradev.almura.feature.exchange.basic.BasicExchange)7 IOException (java.io.IOException)7 BigDecimal (java.math.BigDecimal)7 List (java.util.List)7 UUID (java.util.UUID)7 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)6 ClientboundExchangeGuiResponsePacket (com.almuradev.almura.feature.exchange.network.ClientboundExchangeGuiResponsePacket)5 ClientboundTransactionCompletePacket (com.almuradev.almura.feature.exchange.network.ClientboundTransactionCompletePacket)5