Search in sources :

Example 21 with Result

use of org.jooq.Result in project jOOQ by jOOQ.

the class FirebirdDatabase method getIndexes0.

@Override
protected List<IndexDefinition> getIndexes0() throws SQLException {
    final List<IndexDefinition> result = new ArrayList<>();
    final Rdb$relationConstraints c = RDB$RELATION_CONSTRAINTS.as("c");
    final Rdb$indices i = RDB$INDICES.as("i");
    final Rdb$indexSegments s = RDB$INDEX_SEGMENTS.as("s");
    Map<Record, Result<Record>> indexes = create().select(s.rdb$indices().RDB$RELATION_NAME.trim().as(i.RDB$RELATION_NAME), s.rdb$indices().RDB$INDEX_NAME.trim().as(i.RDB$INDEX_NAME), s.rdb$indices().RDB$UNIQUE_FLAG, s.RDB$FIELD_NAME.trim().as(s.RDB$FIELD_NAME), s.RDB$FIELD_POSITION).from(s).where(s.rdb$indices().RDB$INDEX_NAME.notIn(select(c.RDB$CONSTRAINT_NAME).from(c))).orderBy(s.rdb$indices().RDB$RELATION_NAME, s.rdb$indices().RDB$INDEX_NAME, s.RDB$FIELD_POSITION).fetchGroups(new Field[] { i.RDB$RELATION_NAME, i.RDB$INDEX_NAME, i.RDB$UNIQUE_FLAG }, new Field[] { s.RDB$FIELD_NAME, s.RDB$FIELD_POSITION });
    indexLoop: for (Entry<Record, Result<Record>> entry : indexes.entrySet()) {
        final Record index = entry.getKey();
        final Result<Record> columns = entry.getValue();
        final SchemaDefinition schema = getSchemata().get(0);
        final String indexName = index.get(i.RDB$INDEX_NAME);
        final String tableName = index.get(i.RDB$RELATION_NAME);
        final TableDefinition table = getTable(schema, tableName);
        if (table == null)
            continue indexLoop;
        final boolean unique = index.get(i.RDB$UNIQUE_FLAG, boolean.class);
        // [#6310] [#6620] Function-based indexes are not yet supported
        for (Record column : columns) if (table.getColumn(column.get(s.RDB$FIELD_NAME)) == null)
            continue indexLoop;
        result.add(new AbstractIndexDefinition(schema, indexName, table, unique) {

            List<IndexColumnDefinition> indexColumns = new ArrayList<>();

            {
                for (Record column : columns) {
                    indexColumns.add(new DefaultIndexColumnDefinition(this, table.getColumn(column.get(s.RDB$FIELD_NAME)), SortOrder.ASC, column.get(s.RDB$FIELD_POSITION, int.class)));
                }
            }

            @Override
            protected List<IndexColumnDefinition> getIndexColumns0() {
                return indexColumns;
            }
        });
    }
    return result;
}
Also used : SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) Rdb$indexSegments(org.jooq.meta.firebird.rdb.tables.Rdb$indexSegments) Result(org.jooq.Result) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) Entry(java.util.Map.Entry) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) Rdb$indices(org.jooq.meta.firebird.rdb.tables.Rdb$indices) TableDefinition(org.jooq.meta.TableDefinition) Record(org.jooq.Record) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) Rdb$relationConstraints(org.jooq.meta.firebird.rdb.tables.Rdb$relationConstraints)

Example 22 with Result

use of org.jooq.Result in project jOOQ by jOOQ.

the class H2Database method getIndexes0.

@Override
protected List<IndexDefinition> getIndexes0() throws SQLException {
    List<IndexDefinition> result = new ArrayList<>();
    // Same implementation as in HSQLDBDatabase and MySQLDatabase
    Map<Record, Result<Record>> indexes = indexes().fetchGroups(new Field[] { INDEXES.TABLE_SCHEMA, INDEXES.TABLE_NAME, INDEXES.INDEX_NAME, INDEXES.NON_UNIQUE }, new Field[] { INDEXES.COLUMN_NAME, INDEXES.ORDINAL_POSITION });
    indexLoop: for (Entry<Record, Result<Record>> entry : indexes.entrySet()) {
        final Record index = entry.getKey();
        final Result<Record> columns = entry.getValue();
        final SchemaDefinition tableSchema = getSchema(index.get(INDEXES.TABLE_SCHEMA));
        if (tableSchema == null)
            continue indexLoop;
        final String indexName = index.get(INDEXES.INDEX_NAME);
        final String tableName = index.get(INDEXES.TABLE_NAME);
        final TableDefinition table = getTable(tableSchema, tableName);
        if (table == null)
            continue indexLoop;
        final boolean unique = !index.get(INDEXES.NON_UNIQUE, boolean.class);
        // [#6310] [#6620] Function-based indexes are not yet supported
        for (Record column : columns) if (table.getColumn(column.get(INDEXES.COLUMN_NAME)) == null)
            continue indexLoop;
        result.add(new AbstractIndexDefinition(tableSchema, indexName, table, unique) {

            List<IndexColumnDefinition> indexColumns = new ArrayList<>();

            {
                for (Record column : columns) {
                    indexColumns.add(new DefaultIndexColumnDefinition(this, table.getColumn(column.get(INDEXES.COLUMN_NAME)), SortOrder.ASC, column.get(INDEXES.ORDINAL_POSITION, int.class)));
                }
            }

            @Override
            protected List<IndexColumnDefinition> getIndexColumns0() {
                return indexColumns;
            }
        });
    }
    return result;
}
Also used : SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) Result(org.jooq.Result) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) Entry(java.util.Map.Entry) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) TableDefinition(org.jooq.meta.TableDefinition) Record(org.jooq.Record) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 23 with Result

use of org.jooq.Result in project jOOQ by jOOQ.

the class SQLiteDatabase method getIndexes0.

@Override
protected List<IndexDefinition> getIndexes0() throws SQLException {
    final List<IndexDefinition> result = new ArrayList<>();
    final Field<String> fIndexName = field("il.name", String.class).as("index_name");
    final Field<Boolean> fUnique = field("il.\"unique\"", boolean.class).as("unique");
    final Field<Integer> fSeqno = field("ii.seqno", int.class).add(one()).as("seqno");
    final Field<String> fColumnName = field("ii.name", String.class).as("column_name");
    Map<Record, Result<Record>> indexes = create().select(SQLiteMaster.NAME, fIndexName, fUnique, fSeqno, fColumnName).from(SQLITE_MASTER, table("pragma_index_list({0})", SQLiteMaster.NAME).as("il"), table("pragma_index_info(il.name)").as("ii")).where(SQLiteMaster.TYPE.eq(inline("table"))).and(getIncludeSystemIndexes() ? noCondition() : field("il.origin", VARCHAR).notIn(inline("pk"), inline("u"))).orderBy(1, 2, 4).fetchGroups(new Field[] { SQLiteMaster.NAME, fIndexName, fUnique }, new Field[] { fColumnName, fSeqno });
    indexLoop: for (Entry<Record, Result<Record>> entry : indexes.entrySet()) {
        final Record index = entry.getKey();
        final Result<Record> columns = entry.getValue();
        final SchemaDefinition tableSchema = getSchemata().get(0);
        if (tableSchema == null)
            continue indexLoop;
        final String indexName = index.get(fIndexName);
        final String tableName = index.get(SQLiteMaster.NAME);
        final TableDefinition table = getTable(tableSchema, tableName);
        if (table == null)
            continue indexLoop;
        final boolean unique = index.get(fUnique);
        // [#6310] [#6620] Function-based indexes are not yet supported
        for (Record column : columns) if (table.getColumn(column.get(fColumnName)) == null)
            continue indexLoop;
        result.add(new AbstractIndexDefinition(tableSchema, indexName, table, unique) {

            List<IndexColumnDefinition> indexColumns = new ArrayList<>();

            {
                for (Record column : columns) {
                    indexColumns.add(new DefaultIndexColumnDefinition(this, table.getColumn(column.get(fColumnName)), SortOrder.ASC, column.get(fSeqno, int.class)));
                }
            }

            @Override
            protected List<IndexColumnDefinition> getIndexColumns0() {
                return indexColumns;
            }
        });
    }
    return result;
}
Also used : SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) Result(org.jooq.Result) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) Entry(java.util.Map.Entry) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) TableDefinition(org.jooq.meta.TableDefinition) Record(org.jooq.Record) List(java.util.List) ArrayList(java.util.ArrayList)

Example 24 with Result

use of org.jooq.Result in project jOOQ by jOOQ.

the class AbstractResult method formatChart.

@SuppressWarnings("unchecked")
@Override
public final void formatChart(Writer writer, ChartFormat format) {
    Result<R> result;
    if (this instanceof Result)
        result = (Result<R>) this;
    else if (this instanceof Cursor)
        result = ((Cursor<R>) this).fetch();
    else
        throw new IllegalStateException();
    try {
        if (result.isEmpty()) {
            writer.append("No data available");
            return;
        }
        DSLContext ctx = configuration.dsl();
        FormattingProvider fp = configuration.formattingProvider();
        Field<?> category = fields.field(format.category());
        TreeMap<Object, Result<R>> groups = new TreeMap<>(result.intoGroups(format.category()));
        if (!format.categoryAsText()) {
            if (Date.class.isAssignableFrom(category.getType())) {
                Date categoryMin = (Date) groups.firstKey();
                Date categoryMax = (Date) groups.lastKey();
                for (Date i = categoryMin; i.before(categoryMax); i = new Date(i.getYear(), i.getMonth(), i.getDate() + 1)) if (!groups.containsKey(i))
                    groups.put(i, (Result<R>) ctx.newResult(fields.fields.fields));
            }
        }
        List<?> categories = new ArrayList<>(groups.keySet());
        int categoryPadding = 1;
        int categoryWidth = 0;
        for (Object o : categories) categoryWidth = Math.max(categoryWidth, fp.width("" + o));
        double axisMin = Double.POSITIVE_INFINITY;
        double axisMax = Double.NEGATIVE_INFINITY;
        for (Result<R> values : groups.values()) {
            double sum = 0;
            for (int i = 0; i < format.values().length; i++) {
                if (format.display() == Display.DEFAULT)
                    sum = 0;
                for (Record r : values) sum = sum + r.get(format.values()[i], double.class);
                if (sum < axisMin)
                    axisMin = sum;
                if (sum > axisMax)
                    axisMax = sum;
            }
        }
        int verticalLegendWidth = format.showVerticalLegend() ? (format.display() == Display.HUNDRED_PERCENT_STACKED) ? fp.width(format.percentFormat().format(100.0)) : Math.max(format.numericFormat().format(axisMin).length(), format.numericFormat().format(axisMax).length()) : 0;
        int horizontalLegendHeight = format.showHorizontalLegend() ? 1 : 0;
        int verticalBorderWidth = format.showVerticalLegend() ? 1 : 0;
        int horizontalBorderHeight = format.showHorizontalLegend() ? 1 : 0;
        int chartHeight = format.height() - horizontalLegendHeight - horizontalBorderHeight;
        int chartWidth = format.width() - verticalLegendWidth - verticalBorderWidth;
        double barWidth = (double) chartWidth / groups.size();
        double axisStep = (axisMax - axisMin) / (chartHeight - 1);
        for (int y = chartHeight - 1; y >= 0; y--) {
            double axisLegend = axisMax - (axisStep * (chartHeight - 1 - y));
            double axisLegendPercent = (axisLegend - axisMin) / (axisMax - axisMin);
            if (format.showVerticalLegend()) {
                String axisLegendString = (format.display() == Display.HUNDRED_PERCENT_STACKED) ? format.percentFormat().format(axisLegendPercent * 100.0) : format.numericFormat().format(axisLegend);
                for (int x = fp.width(axisLegendString); x < verticalLegendWidth; x++) writer.write(' ');
                writer.write(axisLegendString);
                for (int x = 0; x < verticalBorderWidth; x++) writer.write('|');
            }
            for (int x = 0; x < chartWidth; x++) {
                int index = (int) (x / barWidth);
                Result<R> group = groups.get(categories.get(index));
                double[] values = new double[format.values().length];
                for (Record record : group) for (int i = 0; i < values.length; i++) values[i] = values[i] + record.get(format.values()[i], double.class);
                if (format.display() == Display.STACKED || format.display() == Display.HUNDRED_PERCENT_STACKED)
                    for (int i = 1; i < values.length; i++) values[i] = values[i] + values[i - 1];
                if (format.display() == Display.HUNDRED_PERCENT_STACKED)
                    for (int i = 0; i < values.length; i++) values[i] = values[i] / values[values.length - 1];
                int shadeIndex = -1;
                for (int i = values.length - 1; i >= 0; i--) if ((format.display() == Display.HUNDRED_PERCENT_STACKED ? axisLegendPercent : axisLegend) > values[i])
                    break;
                else
                    shadeIndex = i;
                if (shadeIndex == -1)
                    writer.write(' ');
                else
                    writer.write(format.shades()[shadeIndex % format.shades().length]);
            }
            writer.write(format.newline());
        }
        if (format.showHorizontalLegend()) {
            for (int y = 0; y < horizontalBorderHeight; y++) {
                if (format.showVerticalLegend()) {
                    for (int x = 0; x < verticalLegendWidth; x++) writer.write('-');
                    for (int x = 0; x < verticalBorderWidth; x++) writer.write('+');
                }
                for (int x = 0; x < chartWidth; x++) writer.write('-');
                writer.write(format.newline());
            }
            for (int y = 0; y < horizontalLegendHeight; y++) {
                if (format.showVerticalLegend()) {
                    for (int x = 0; x < verticalLegendWidth; x++) writer.write(' ');
                    for (int x = 0; x < verticalBorderWidth; x++) writer.write('|');
                }
                double rounding = 0.0;
                for (double x = 0.0; x < chartWidth; ) {
                    String label = "" + categories.get((int) (x / barWidth));
                    int width = fp.width(label);
                    double padding = Math.max(categoryPadding, (barWidth - width) / 2);
                    rounding = (rounding + padding - Math.floor(padding)) % 1;
                    x = x + (padding + rounding);
                    for (int i = 0; i < (int) (padding + rounding); i++) writer.write(' ');
                    x = x + width;
                    if (x >= chartWidth)
                        break;
                    writer.write(label);
                    rounding = (rounding + padding - Math.floor(padding)) % 1;
                    x = x + (padding + rounding);
                    for (int i = 0; i < (int) (padding + rounding); i++) writer.write(' ');
                }
                writer.write(format.newline());
            }
        }
    } catch (java.io.IOException e) {
        throw new IOException("Exception while writing Chart", e);
    }
}
Also used : FormattingProvider(org.jooq.FormattingProvider) ArrayList(java.util.ArrayList) DSLContext(org.jooq.DSLContext) IOException(org.jooq.exception.IOException) Cursor(org.jooq.Cursor) TreeMap(java.util.TreeMap) Date(java.sql.Date) Result(org.jooq.Result) TableRecord(org.jooq.TableRecord) Record(org.jooq.Record)

Example 25 with Result

use of org.jooq.Result in project Almura by AlmuraDev.

the class ServerExchangeManager method handleModifyListItems.

public void handleModifyListItems(final Player player, final String id, final List<InventoryAction> actions) {
    checkNotNull(player);
    checkNotNull(id);
    checkNotNull(actions);
    checkState(!actions.isEmpty());
    final Exchange axs = this.getExchange(id).orElse(null);
    if (axs == null) {
        this.logger.error("Player '{}' attempted to list items for exchange '{}' but the server has no knowledge of it. Syncing exchange " + "registry...", player.getName(), id);
        this.syncExchangeRegistryTo(player);
        return;
    }
    final UUID seller = player.getUniqueId();
    final EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
    final IItemHandler simulatedInventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
    // Inventory -> Listing
    final List<InventoryAction> toListingActions = actions.stream().filter(a -> a.getDirection() == InventoryAction.Direction.TO_LISTING).collect(Collectors.toList());
    final List<VanillaStack> toListingStacks = new ArrayList<>();
    final List<VanillaStack> unknownInventoryStacks = new ArrayList<>();
    final List<VanillaStack> leftoverToListingStacks = new ArrayList<>();
    for (InventoryAction toListingAction : toListingActions) {
        final VanillaStack stack = toListingAction.getStack();
        int amountLeft = stack.getQuantity();
        boolean matched = false;
        for (int j = 0; j < simulatedInventory.getSlots(); j++) {
            final ItemStack slotStack = simulatedInventory.getStackInSlot(j);
            if (ItemHandlerHelper.canItemStacksStack(slotStack, stack.asRealStack())) {
                amountLeft -= simulatedInventory.extractItem(j, amountLeft, false).getCount();
                matched = true;
            }
            if (amountLeft <= 0) {
                break;
            }
        }
        if (!matched) {
            unknownInventoryStacks.add(stack);
        } else {
            if (amountLeft > 0) {
                final VanillaStack copyStack = stack.copy();
                copyStack.setQuantity(amountLeft);
                leftoverToListingStacks.add(copyStack);
            }
            final VanillaStack copyStack = stack.copy();
            copyStack.setQuantity(stack.getQuantity() - amountLeft);
            if (copyStack.getQuantity() != 0) {
                toListingStacks.add(copyStack);
            }
        }
    }
    // Listing -> Inventory
    final List<InventoryAction> toInventoryActions = actions.stream().filter(a -> a.getDirection() == InventoryAction.Direction.TO_INVENTORY).collect(Collectors.toList());
    final List<VanillaStack> listingNotFoundStacks = new ArrayList<>();
    final List<ListItem> desyncToInventoryStacks = new ArrayList<>();
    final List<ListItem> toInventoryStacks = new ArrayList<>();
    final List<ListItem> partialToInventoryStacks = new ArrayList<>();
    final List<ListItem> currentListItems = axs.getListItemsFor(player.getUniqueId()).orElse(null);
    if (!toInventoryActions.isEmpty()) {
        if (currentListItems == null || currentListItems.isEmpty()) {
            this.logger.error("Player '{}' attempted to move listings back to the inventory for exchange '{}' but the server knows of no " + "listings for them. This could be a de-sync or an exploit. Printing stacks...", player.getName(), axs.getId());
            this.network.sendTo(player, new ClientboundListItemsResponsePacket(axs.getId(), null));
            this.printStacksToConsole(toInventoryActions.stream().map(InventoryAction::getStack).collect(Collectors.toList()));
        } else {
            for (final InventoryAction action : toInventoryActions) {
                final VanillaStack stack = action.getStack();
                ListItem found = null;
                for (final ListItem listItem : currentListItems) {
                    if (ItemHandlerHelper.canItemStacksStack(stack.asRealStack(), listItem.asRealStack())) {
                        found = listItem;
                        break;
                    }
                }
                // Unknown listing
                if (found == null) {
                    listingNotFoundStacks.add(stack);
                    continue;
                }
                ListItem toRemove = found.copy();
                // Listing quantity mismatch (tracking this to let the user know)
                if (found.getQuantity() < stack.getQuantity()) {
                    desyncToInventoryStacks.add(found);
                    toRemove.setQuantity(found.getQuantity());
                } else {
                    toRemove.setQuantity(stack.getQuantity());
                }
                final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(simulatedInventory, toRemove.asRealStack(), true);
                // Simulated a partial stack insertion
                if (!resultStack.isEmpty()) {
                    final ListItem copyStack = toRemove.copy();
                    copyStack.setQuantity(resultStack.getCount());
                    partialToInventoryStacks.add(copyStack);
                }
                final ListItem copyStack = toRemove.copy();
                copyStack.setQuantity(toRemove.getQuantity() - resultStack.getCount());
                toInventoryStacks.add(copyStack);
            }
        }
    }
    // This may seem quite weird but we need to clear out the listing items reference for this player across the board to await what the results
    // are from the database to ensure we're 1:1 in sync. Otherwise, the Exchange would keep selling..
    axs.putListItemsFor(seller, null);
    axs.putForSaleItemsFor(seller, null);
    Sponge.getServer().getOnlinePlayers().stream().filter(p -> p.getUniqueId() != seller).forEach(p -> this.network.sendTo(p, new ClientboundForSaleFilterRequestPacket(axs.getId())));
    this.scheduler.createTaskBuilder().async().execute(() -> {
        try (final DSLContext context = this.databaseManager.createContext(true)) {
            final Iterator<VanillaStack> listingIter = toListingStacks.iterator();
            int index = 0;
            // New listing
            while (listingIter.hasNext()) {
                final VanillaStack stack = listingIter.next();
                final ItemStack realStack = stack.asRealStack();
                ListItem found = null;
                if (currentListItems != null) {
                    found = currentListItems.stream().filter(item -> ItemHandlerHelper.canItemStacksStack(realStack, item.asRealStack())).findAny().orElse(null);
                }
                if (found == null) {
                    final AxsListItemRecord itemRecord = ExchangeQueries.createInsertListItem(axs.getId(), Instant.now(), seller, realStack.getItem(), stack.getQuantity(), realStack.getMetadata(), index).build(context).fetchOne();
                    if (itemRecord == null) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' submitted a new list item for exchange '{}' to the database but it failed. " + "Discarding changes and printing stack...", player.getName(), id);
                        this.printStacksToConsole(Lists.newArrayList(stack));
                        continue;
                    }
                    final NBTTagCompound compound = stack.getCompound();
                    if (compound == null) {
                        continue;
                    }
                    final AxsListItemDataRecord dataRecord = ExchangeQueries.createInsertItemData(itemRecord.getRecNo(), compound).build(context).fetchOne();
                    if (dataRecord == null) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' submitted data for item record '{}' for exchange '{}' but it failed. " + "Discarding changes...", player.getName(), itemRecord.getRecNo(), id);
                        ExchangeQueries.createDeleteListItem(itemRecord.getRecNo()).build(context).execute();
                    }
                } else {
                    final int result = ExchangeQueries.createUpdateListItem(found.getRecord(), stack.getQuantity() + found.getQuantity(), index).build(context).execute();
                    if (result == 0) {
                        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 add quantity to list item '{}' for exchange '{}' but it failed. " + "Discarding changes...", player.getName(), found.getRecord(), id);
                        listingIter.remove();
                    }
                }
                index++;
            }
            for (final ListItem next : toInventoryStacks) {
                ListItem existingStack = null;
                for (final ListItem stack : currentListItems) {
                    if (next.getRecord() == stack.getRecord()) {
                        existingStack = stack;
                        break;
                    }
                }
                final int diff = existingStack.getQuantity() - next.getQuantity();
                if (diff == 0) {
                    final int result = ExchangeQueries.createUpdateListItemIsHidden(next.getRecord(), true).build(context).execute();
                    if (result == 0) {
                        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 remove list item '{}' for exchange '{}' but it failed. Discarding " + "changes...", player.getName(), next.getRecord(), id);
                    }
                // Update partial listings
                } else {
                    final int result = ExchangeQueries.createUpdateListItem(next.getRecord(), diff, next.getIndex()).build(context).execute();
                    if (result == 0) {
                        this.notificationManager.sendWindowMessage(player, Text.of("Exchange"), Text.of("Critical error encountered, check the server console for more details!"));
                        this.logger.error("Player '{}' removed quantity from list item '{}' for exchange '{}' to the database but it " + "failed. Discarding changes...", player.getName(), next.getRecord(), id);
                    }
                }
            }
            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 Player sellerPlayer = Sponge.getServer().getPlayer(seller).orElse(null);
                if (sellerPlayer != null) {
                    final IItemHandler inventory = ((EntityPlayerMP) sellerPlayer).getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
                    // Add stacks from listings
                    for (final ListItem stack : toInventoryStacks) {
                        final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, stack.asRealStack(), false);
                        if (!resultStack.isEmpty()) {
                        // TODO Their inventory changed since simulation. Best case scenario we toss it on the ground
                        }
                    }
                } else {
                // TODO They went offline on us. It is a very rare off-case. Half tempted to print what they should have got and let
                // TODO an admin deal with it
                }
                final List<ListItem> listItems = new ArrayList<>();
                listItemResults.forEach(result -> listItems.addAll(this.parseListItemsFrom(result)));
                final List<ForSaleItem> forSaleItems = new ArrayList<>();
                forSaleItemResults.forEach(result -> forSaleItems.addAll(this.parseForSaleItemsFrom(listItems, result)));
                // TODO Build a notification that says...
                // TODO  - Stacks requested to go to a listing but inventory can't fulfill it
                // TODO  - Stacks requested to go to the inventory but listings aren't found
                // TODO  - Stacks requested to go to the inventory but the listing couldn't fulfill it so we took what we could
                axs.putListItemsFor(seller, listItems);
                axs.putForSaleItemsFor(seller, forSaleItems);
                if (sellerPlayer != null) {
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsResponsePacket(axs.getId(), listItems));
                    this.network.sendTo(sellerPlayer, new ClientboundListItemsSaleStatusPacket(axs.getId(), forSaleItems, null));
                }
                Sponge.getServer().getOnlinePlayers().forEach(p -> this.network.sendTo(p, new ClientboundForSaleFilterRequestPacket(axs.getId())));
            }).submit(this.container);
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }).submit(this.container);
}
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) ArrayList(java.util.ArrayList) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsResponsePacket) AxsListItemRecord(com.almuradev.generated.axs.tables.records.AxsListItemRecord) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) BasicForSaleItem(com.almuradev.almura.feature.exchange.basic.listing.BasicForSaleItem) AxsForSaleItem(com.almuradev.generated.axs.tables.AxsForSaleItem) ForSaleItem(com.almuradev.almura.feature.exchange.listing.ForSaleItem) Iterator(java.util.Iterator) ClientboundListItemsSaleStatusPacket(com.almuradev.almura.feature.exchange.network.ClientboundListItemsSaleStatusPacket) UUID(java.util.UUID) Player(org.spongepowered.api.entity.living.player.Player) IItemHandler(net.minecraftforge.items.IItemHandler) DSLContext(org.jooq.DSLContext) BasicExchange(com.almuradev.almura.feature.exchange.basic.BasicExchange) Results(org.jooq.Results) AxsListItemDataRecord(com.almuradev.generated.axs.tables.records.AxsListItemDataRecord) 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)

Aggregations

Result (org.jooq.Result)31 Record (org.jooq.Record)24 ArrayList (java.util.ArrayList)23 List (java.util.List)22 Collectors (java.util.stream.Collectors)17 DSLContext (org.jooq.DSLContext)17 BigDecimal (java.math.BigDecimal)13 SQLException (java.sql.SQLException)13 Map (java.util.Map)13 Timestamp (java.sql.Timestamp)12 Optional (java.util.Optional)12 Stream (java.util.stream.Stream)12 Lists (com.google.common.collect.Lists)11 HashMap (java.util.HashMap)11 UUID (java.util.UUID)11 IOException (java.io.IOException)10 Iterator (java.util.Iterator)10 Singleton (javax.inject.Singleton)10 Almura (com.almuradev.almura.Almura)9 ServerNotificationManager (com.almuradev.almura.feature.notification.ServerNotificationManager)9