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 org.openstreetmap.josm.Main;
007import org.openstreetmap.josm.actions.SaveAction;
008import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
009import org.openstreetmap.josm.gui.progress.ProgressMonitor;
010import org.openstreetmap.josm.tools.CheckParameterUtil;
011
012/**
013 * SaveLayerTask saves the data managed by an {@link org.openstreetmap.josm.gui.layer.AbstractModifiableLayer} to the
014 * {@link org.openstreetmap.josm.gui.layer.Layer#getAssociatedFile()}.
015 *
016 * <pre>
017 *     ExecutorService executorService = ...
018 *     SaveLayerTask task = new SaveLayerTask(layer, monitor);
019 *     Future&lt;?&gt; taskFuture = executorService.submit(task)
020 *     try {
021 *        // wait for the task to complete
022 *        taskFuture.get();
023 *     } catch (Exception e) {
024 *        e.printStackTrace();
025 *     }
026 * </pre>
027 */
028public class SaveLayerTask extends AbstractIOTask {
029    private final SaveLayerInfo layerInfo;
030    private final ProgressMonitor parentMonitor;
031
032    /**
033     *
034     * @param layerInfo information about the layer to be saved to save. Must not be null.
035     * @param monitor the monitor. Set to {@link NullProgressMonitor#INSTANCE} if null
036     * @throws IllegalArgumentException if layer is null
037     */
038    protected SaveLayerTask(SaveLayerInfo layerInfo, ProgressMonitor monitor) {
039        CheckParameterUtil.ensureParameterNotNull(layerInfo, "layerInfo");
040        if (monitor == null) {
041            monitor = NullProgressMonitor.INSTANCE;
042        }
043        this.layerInfo =  layerInfo;
044        this.parentMonitor = monitor;
045    }
046
047    @Override
048    public void run() {
049        try {
050            parentMonitor.subTask(tr("Saving layer to ''{0}'' ...", layerInfo.getFile().toString()));
051            if (!SaveAction.doSave(layerInfo.getLayer(), layerInfo.getFile(), layerInfo.isDoCheckSaveConditions())) {
052                setFailed(true);
053                return;
054            }
055            if (!isCanceled()) {
056                layerInfo.getLayer().onPostSaveToFile();
057            }
058        } catch (RuntimeException e) {
059            Main.error(e);
060            setLastException(e);
061        }
062    }
063
064    @Override
065    public void cancel() {
066        setCanceled(true);
067    }
068}