OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.sql.view.list;

import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSelect.LockStrength;
import org.openconcerto.sql.model.SQLSyntax;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.utils.ReOrder;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.utils.ExceptionUtils;
import org.openconcerto.utils.NumberUtils;
import org.openconcerto.utils.SleepingQueue;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import javax.swing.SwingUtilities;

public final class MoveQueue extends SleepingQueue {

    private final ITableModel tableModel;

    MoveQueue(ITableModel model) {
        super(MoveQueue.class.getSimpleName() + " on " + model);
        this.tableModel = model;
    }

    public Future<?> move(final List<? extends SQLRowAccessor> rows, final int inc) {
        if (inc == 0 || rows.size() == 0)
            return null;

        final boolean after = inc > 0;
        SQLRowAccessor outerR = null;
        for (final SQLRowAccessor r : rows) {
            if (outerR == null) {
                outerR = r;
            } else {
                final int compare = r.getOrder().compareTo(outerR.getOrder());
                if (after && compare > 0 || !after && compare < 0) {
                    outerR = r;
                }
            }
        }
        final int id = outerR.getID();
        return this.put(new Runnable() {
            public void run() {
                final FutureTask<ListSQLLine> destID = new FutureTask<ListSQLLine>(new Callable<ListSQLLine>() {
                    @Override
                    public ListSQLLine call() {
                        return MoveQueue.this.tableModel.getDestLine(id, inc);
                    }
                });
                MoveQueue.this.tableModel.invokeLater(destID);
                try {
                    if (destID.get() != null) {
                        SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, Exception>() {
                            @Override
                            public Object handle(SQLDataSource ds) throws Exception {
                                moveQuick(rows, after, destID.get().getRowAccessor().asRow());
                                return null;
                            }
                        });
                    }
                } catch (Exception e) {
                    throw ExceptionUtils.createExn(IllegalStateException.class, "move failed", e);
                }
            }
        });
    }

    // row index as returned by JTable.DropLocation.getRow()
    public Future<?> moveTo(final List<? extends Number> rows, final int rowIndex) {
        if (rows.size() == 0)
            return null;

        // the user just dropped rows to move on rowIndex, find out right away which row that is.
        // (we used to go through the UpdateQueue which could result in the destination row the user
        // saw being replaced by a different row)
        assert rowIndex >= 0;
        assert SwingUtilities.isEventDispatchThread();
        final int rowCount = this.tableModel.getRowCount();
        final boolean after = rowIndex >= rowCount;
        final int index = after ? rowCount - 1 : rowIndex;
        final SQLRowAccessor line = this.tableModel.getRow(index).getRowAccessor();
        assert line.isFrozen() : "row could change by the time move() is called";

        return this.put(new Runnable() {
            @Override
            public void run() {
                try {
                    SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, Exception>() {
                        @Override
                        public Object handle(SQLDataSource ds) throws Exception {
                            moveQuick(rows, after, line.asRow());
                            return null;
                        }
                    });
                } catch (Exception e) {
                    throw ExceptionUtils.createExn(IllegalStateException.class, "move failed", e);
                }
            }
        });
    }

    final void moveQuick(final List<?> srcRows, final boolean after, final SQLRow destRow) throws SQLException {
        final int rowCount = srcRows.size();
        // if only some rows are moved, update one by one (avoids refreshing the whole list)
        // (getRowCount() is not thread-safe, so use getTotalRowCount())
        if (rowCount < 5 && rowCount < (this.tableModel.getTotalRowCount() / 3)) {
            final SQLTable t = getTable();
            final String orderName = t.getOrderField().getName();
            final SQLRowValues vals = new SQLRowValues(t);
            final List<BigDecimal> orders = ReOrder.getFreeOrderValuesFor(rowCount, after, destRow).get0();
            for (int i = 0; i < rowCount; i++) {
                final Object src = srcRows.get(i);
                vals.put(orderName, orders.get(i)).update(getID(src, t).intValue());
            }
        } else {
            // update all rows at once and refresh the whole list
            moveAtOnce(srcRows, rowCount, after, destRow);
        }
    }

    private static Number getID(final Object o, final SQLTable t) {
        final Number res;
        if (o instanceof SQLRowAccessor) {
            final SQLRowAccessor row = (SQLRowAccessor) o;
            if (row.getTable() != t)
                throw new IllegalArgumentException("Not from the same table : " + row + " != " + t);
            res = row.getIDNumber();
        } else {
            res = (Number) o;
        }
        return res;
    }

    private SQLTable getTable() {
        return this.tableModel.getTable();
    }

    /**
     * Move the passed rows just before or just after the destination row. The current database
     * order of the rows is not used, i.e. after this method returns the order will be that of the
     * passed list, with <code>destRow</code> coming either before or after them all.
     * 
     * @param srcRows rows to reorder.
     * @param after <code>true</code> if the rows should be placed after <code>destRow</code>,
     *        <code>false</code> otherwise.
     * @param destRow <code>srcRows</code> will be placed relative to the order of this row.
     * @throws SQLException if an error occurs.
     */
    static public void moveAtOnce(final List<? extends SQLRowAccessor> srcRows, final boolean after, final SQLRow destRow) throws SQLException {
        moveAtOnce(srcRows, srcRows.size(), after, destRow);
    }

    /**
     * Move the passed rows just before or just after the destination row if needed.
     * 
     * @param ids rows to order.
     * @param after <code>true</code> if the rows should be placed after <code>destRow</code>,
     *        <code>false</code> otherwise.
     * @param destRow <code>srcRows</code> will be placed relative to the order of this row.
     * @param checkBefore if <code>true</code> the current DB order will be checked and if it
     *        matched the passed rows, no change will be made to the DB, <code>false</code> to
     *        always change the orders in the DB.
     * @return if the DB was changed.
     * @throws SQLException if an error occurs.
     */
    static public boolean moveIDsAtOnce(final List<? extends Number> ids, final boolean after, final SQLRow destRow, final boolean checkBefore) throws SQLException {
        final int size = ids.size();
        if (checkBefore) {
            final SQLTable table = destRow.getTable();
            final SQLSelect sel = new SQLSelect(true);
            sel.addSelect(table.getKey());
            sel.addOrder(table);
            sel.setWhere(new Where(table.getKey(), ids));
            // needed since we might update them just after in moveAtOnce(), and it's safer to lock
            // with the most restrictive mode first.
            sel.setLockStrength(LockStrength.UPDATE);
            final List<?> dbOrderedIDs = table.getDBSystemRoot().getDataSource().executeCol(sel.asString());
            if (dbOrderedIDs.size() != size)
                throw new IllegalStateException("Missing rows");
            boolean orderOK = true;
            for (int i = 0; i < size && orderOK; i++) {
                final Number passedID = ids.get(i);
                final Number dbID = (Number) dbOrderedIDs.get(i);
                orderOK = NumberUtils.areNumericallyEqual(passedID, dbID);
            }
            if (orderOK)
                return false;
        }
        moveAtOnce(ids, size, after, destRow);
        return true;
    }

    static private void moveAtOnce(final List<?> srcRows, final int rowCount, final boolean after, final SQLRow destRow) throws SQLException {
        if (rowCount == 0)
            return;
        final SQLTable t = destRow.getTable();

        final List<BigDecimal> freeOrderValues = ReOrder.getFreeOrderValuesFor(rowCount, after, destRow).get0();

        final List<List<String>> newOrdersAndIDs = new ArrayList<List<String>>(rowCount);
        int i = 0;
        final List<Number> ids = rowCount < 10 ? new ArrayList<Number>(rowCount) : null;
        // we go from newOrder and up, so that the passed rows are in ascending order
        for (final Object src : srcRows) {
            final Number srcID = getID(src, t);
            if (ids != null)
                ids.add(srcID);
            final BigDecimal newOrder = freeOrderValues.get(i++);
            newOrdersAndIDs.add(Arrays.asList(srcID.toString(), newOrder.toPlainString()));
        }

        final SQLSyntax syntax = SQLSyntax.get(t);
        final UpdateBuilder update = new UpdateBuilder(t);
        final String constantTableAlias = "newOrdersAndIDs";
        update.addVirtualJoin(syntax.getConstantTable(newOrdersAndIDs, constantTableAlias, Arrays.asList("ID", "newOrder")), constantTableAlias, true, "ID", t.getKey().getName());
        update.setFromVirtualJoinField(t.getOrderField().getName(), constantTableAlias, "newOrder");
        t.getDBSystemRoot().getDataSource().execute(update.asString());

        final List<String> fieldsChanged = Collections.singletonList(t.getOrderField().getName());
        if (ids == null) {
            t.fireTableModified(SQLRow.NONEXISTANT_ID, fieldsChanged);
        } else {
            for (final Number id : ids)
                t.fireTableModified(id.intValue(), fieldsChanged);
        }
    }
}