001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.upload;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.util.Collection;
007import java.util.Collections;
008import java.util.Map;
009
010import javax.swing.JOptionPane;
011
012import org.openstreetmap.josm.data.APIDataSet;
013import org.openstreetmap.josm.data.osm.OsmPrimitive;
014import org.openstreetmap.josm.data.osm.Tagged;
015import org.openstreetmap.josm.data.osm.Way;
016import org.openstreetmap.josm.data.preferences.AbstractProperty;
017import org.openstreetmap.josm.data.preferences.BooleanProperty;
018import org.openstreetmap.josm.gui.ExceptionDialogUtil;
019import org.openstreetmap.josm.gui.MainApplication;
020import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
021import org.openstreetmap.josm.io.NetworkManager;
022import org.openstreetmap.josm.io.OnlineResource;
023import org.openstreetmap.josm.io.OsmApi;
024import org.openstreetmap.josm.io.OsmApiInitializationException;
025import org.openstreetmap.josm.io.OsmTransferCanceledException;
026import org.openstreetmap.josm.tools.Logging;
027import org.openstreetmap.josm.tools.Utils;
028
029/**
030 * Checks certain basic conditions, that are listed in the OSM API
031 * {@link org.openstreetmap.josm.io.Capabilities}.
032 */
033public class ApiPreconditionCheckerHook implements UploadHook {
034    static AbstractProperty<Boolean> PREF_LENGTH_CHECK = new BooleanProperty("upload.check-maxlength-value", true).cached();
035
036    @Override
037    public boolean checkUpload(APIDataSet apiData) {
038        OsmApi api = OsmApi.getOsmApi();
039        try {
040            if (NetworkManager.isOffline(OnlineResource.OSM_API)) {
041                return false;
042            }
043            // FIXME: this should run asynchronously and a progress monitor
044            // should be displayed.
045            api.initialize(NullProgressMonitor.INSTANCE);
046            long maxNodes = api.getCapabilities().getMaxWayNodes();
047            if (maxNodes > 0) {
048                if (!checkMaxNodes(apiData.getPrimitivesToAdd(), maxNodes))
049                    return false;
050                if (!checkMaxNodes(apiData.getPrimitivesToUpdate(), maxNodes))
051                    return false;
052                if (!checkMaxNodes(apiData.getPrimitivesToDelete(), maxNodes))
053                    return false;
054            }
055        } catch (OsmTransferCanceledException e) {
056            Logging.trace(e);
057            return false;
058        } catch (OsmApiInitializationException e) {
059            ExceptionDialogUtil.explainOsmTransferException(e);
060            return false;
061        }
062        return true;
063    }
064
065    private static boolean checkMaxNodes(Collection<OsmPrimitive> primitives, long maxNodes) {
066        for (OsmPrimitive osmPrimitive : primitives) {
067            if (Boolean.TRUE.equals(PREF_LENGTH_CHECK.get()) && !valueLengthCheck(osmPrimitive)) {
068                return false;
069            }
070
071            if (osmPrimitive instanceof Way &&
072                    ((Way) osmPrimitive).getNodesCount() > maxNodes) {
073                JOptionPane.showMessageDialog(
074                        MainApplication.getMainFrame(),
075                        tr("{0} nodes in way {1} exceed the max. allowed number of nodes {2}",
076                                ((Way) osmPrimitive).getNodesCount(),
077                                Long.toString(osmPrimitive.getId()),
078                                maxNodes
079                        ),
080                        tr("API Capabilities Violation"),
081                        JOptionPane.ERROR_MESSAGE
082                );
083                MainApplication.getLayerManager().getEditDataSet().setSelected(Collections.singleton(osmPrimitive));
084                return false;
085            }
086        }
087        return true;
088    }
089
090    /**
091     * Check that the tag values of a primitive are not too long.
092     * @param osmPrimitive the primitive to check
093     * @return false if any tag value of the primitive is too long, true else
094     */
095    private static boolean valueLengthCheck(OsmPrimitive osmPrimitive) {
096        for (Map.Entry<String, String> entry: osmPrimitive.getKeys().entrySet()) {
097            String key = entry.getKey();
098            String value = entry.getValue();
099            if (!Utils.checkCodePointCount(value, Tagged.MAX_TAG_LENGTH)) {
100                if (osmPrimitive.isDeleted()) {
101                    // if OsmPrimitive is going to be deleted we automatically shorten the value
102                    Logging.warn(
103                            tr("Automatically truncating value of tag ''{0}'' on deleted object {1}",
104                                    key,
105                                    Long.toString(osmPrimitive.getId())
106                            )
107                    );
108                    osmPrimitive.put(key, Utils.shortenString(value, Tagged.MAX_TAG_LENGTH));
109                    continue;
110                }
111                JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
112                        tr("Length of value for tag ''{0}'' on object {1} exceeds the max. allowed length {2}. Values length is {3}.",
113                                key, Long.toString(osmPrimitive.getId()), Tagged.MAX_TAG_LENGTH, Utils.getCodePointCount(value)
114                        ),
115                        tr("Precondition violation"),
116                        JOptionPane.ERROR_MESSAGE
117                );
118                MainApplication.getLayerManager().getEditDataSet().setSelected(Collections.singleton(osmPrimitive));
119                return false;
120            }
121        }
122        return true;
123    }
124}