001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.util.ArrayList;
008import java.util.Collection;
009import java.util.List;
010
011import javax.swing.SwingUtilities;
012
013import org.openstreetmap.josm.data.osm.Changeset;
014import org.openstreetmap.josm.data.osm.ChangesetCache;
015import org.openstreetmap.josm.gui.ExceptionDialogUtil;
016import org.openstreetmap.josm.gui.PleaseWaitRunnable;
017import org.openstreetmap.josm.io.OsmApi;
018import org.openstreetmap.josm.io.OsmTransferException;
019import org.xml.sax.SAXException;
020
021/**
022 * A task for closing a collection of changesets.
023 *
024 */
025public class CloseChangesetTask extends PleaseWaitRunnable {
026    private boolean canceled;
027    private Exception lastException;
028    private final Collection<Changeset> changesets;
029    private final List<Changeset> closedChangesets;
030
031    /**
032     * Closes all changesets in <code>changesets</code> if they are not null, if they
033     * are still open and if they have an id &gt; 0. Other changesets in the collection
034     * are ignored.
035     *
036     * @param changesets  the collection of changesets. Empty collection assumes, if null.
037     */
038    public CloseChangesetTask(Collection<Changeset> changesets) {
039        super(tr("Closing changeset"), false /* don't ignore exceptions */);
040        if (changesets == null) {
041            changesets = new ArrayList<>();
042        }
043        this.changesets = changesets;
044        this.closedChangesets = new ArrayList<>();
045    }
046
047    @Override
048    protected void cancel() {
049        this.canceled = true;
050        OsmApi.getOsmApi().cancel();
051    }
052
053    @Override
054    protected void finish() {
055        if (canceled)
056            return;
057        if (lastException != null) {
058            ExceptionDialogUtil.explainException(lastException);
059        }
060        SwingUtilities.invokeLater(() -> ChangesetCache.getInstance().update(closedChangesets));
061    }
062
063    @Override
064    protected void realRun() throws SAXException, IOException, OsmTransferException {
065        try {
066            for (Changeset cs: changesets) {
067                if (canceled) return;
068                if (cs == null || cs.getId() <= 0 || !cs.isOpen()) {
069                    continue;
070                }
071                getProgressMonitor().subTask(tr("Closing changeset {0}", cs.getId()));
072                OsmApi.getOsmApi().closeChangeset(cs, getProgressMonitor().createSubTaskMonitor(1, false));
073                closedChangesets.add(cs);
074            }
075        } catch (OsmTransferException e) {
076            if (canceled)
077                return;
078            lastException = e;
079        }
080    }
081}