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