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.util.Optional;
007
008import org.openstreetmap.josm.actions.SaveAction;
009import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
010import org.openstreetmap.josm.gui.progress.ProgressMonitor;
011import org.openstreetmap.josm.tools.CheckParameterUtil;
012import org.openstreetmap.josm.tools.JosmRuntimeException;
013import org.openstreetmap.josm.tools.Logging;
014
015/**
016 * SaveLayerTask saves the data managed by an {@link org.openstreetmap.josm.gui.layer.AbstractModifiableLayer} to the
017 * {@link org.openstreetmap.josm.gui.layer.Layer#getAssociatedFile()}.
018 *
019 * <pre>
020 *     ExecutorService executorService = ...
021 *     SaveLayerTask task = new SaveLayerTask(layer, monitor);
022 *     Future&lt;?&gt; taskFuture = executorService.submit(task)
023 *     try {
024 *        // wait for the task to complete
025 *        taskFuture.get();
026 *     } catch (Exception e) {
027 *        e.printStackTrace();
028 *     }
029 * </pre>
030 */
031public class SaveLayerTask extends AbstractIOTask {
032    private final SaveLayerInfo layerInfo;
033    private final ProgressMonitor parentMonitor;
034
035    /**
036     *
037     * @param layerInfo information about the layer to be saved to save. Must not be null.
038     * @param monitor the monitor. Set to {@link NullProgressMonitor#INSTANCE} if null
039     * @throws IllegalArgumentException if layer is null
040     */
041    protected SaveLayerTask(SaveLayerInfo layerInfo, ProgressMonitor monitor) {
042        CheckParameterUtil.ensureParameterNotNull(layerInfo, "layerInfo");
043        this.layerInfo = layerInfo;
044        this.parentMonitor = Optional.ofNullable(monitor).orElse(NullProgressMonitor.INSTANCE);
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 (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
059            Logging.error(e);
060            setLastException(e);
061        }
062    }
063
064    @Override
065    public void cancel() {
066        setCanceled(true);
067    }
068}