001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data;
003
004import java.util.ArrayList;
005import java.util.Collection;
006import java.util.Comparator;
007import java.util.HashMap;
008import java.util.HashSet;
009import java.util.LinkedList;
010import java.util.List;
011import java.util.Map;
012import java.util.Set;
013import java.util.Stack;
014import java.util.stream.Collectors;
015import java.util.stream.Stream;
016
017import org.openstreetmap.josm.data.conflict.ConflictCollection;
018import org.openstreetmap.josm.data.osm.CyclicUploadDependencyException;
019import org.openstreetmap.josm.data.osm.DataSet;
020import org.openstreetmap.josm.data.osm.IPrimitive;
021import org.openstreetmap.josm.data.osm.Node;
022import org.openstreetmap.josm.data.osm.OsmPrimitive;
023import org.openstreetmap.josm.data.osm.OsmPrimitiveComparator;
024import org.openstreetmap.josm.data.osm.PrimitiveId;
025import org.openstreetmap.josm.data.osm.Relation;
026import org.openstreetmap.josm.data.osm.RelationMember;
027import org.openstreetmap.josm.data.osm.Way;
028import org.openstreetmap.josm.tools.Utils;
029
030/**
031 * Represents a collection of {@link OsmPrimitive}s which should be uploaded to the API.
032 * The collection is derived from the modified primitives of an {@link DataSet} and it provides methods
033 * for sorting the objects in upload order.
034 * @since 2025
035 */
036public class APIDataSet {
037    private List<OsmPrimitive> toAdd;
038    private final List<OsmPrimitive> toUpdate;
039    private List<OsmPrimitive> toDelete;
040
041    /**
042     * The type of operation we can perform with OSM API on a primitive.
043     * @since 13161
044     */
045    public enum APIOperation {
046        /** Add a new primitive */
047        ADD,
048        /** Update an existing primitive */
049        UPDATE,
050        /** Delete an existing primitive */
051        DELETE;
052
053        /**
054         * Determines the API operation to perform on a primitive.
055         * @param osm OSM primitive
056         * @return the API operation to perform on {@code osm}
057         */
058        public static APIOperation of(OsmPrimitive osm) {
059            if (osm.isNewOrUndeleted() && !osm.isDeleted()) {
060                return ADD;
061            } else if (osm.isModified() && !osm.isDeleted()) {
062                return UPDATE;
063            } else if (osm.isDeleted() && !osm.isNew() && osm.isModified() && osm.isVisible()) {
064                return DELETE;
065            }
066            return null;
067        }
068    }
069
070    /**
071     * creates a new empty data set
072     */
073    public APIDataSet() {
074        toAdd = new LinkedList<>();
075        toUpdate = new LinkedList<>();
076        toDelete = new LinkedList<>();
077    }
078
079    /**
080     * initializes the API data set with the modified primitives in <code>ds</code>
081     *
082     * @param ds the data set. Ignored, if null.
083     */
084    public void init(DataSet ds) {
085        if (ds == null) return;
086        init(ds.allPrimitives());
087    }
088
089    /**
090     * Initializes the API data set with the modified primitives, ignores unmodified primitives.
091     *
092     * @param primitives the primitives
093     */
094    public final void init(Collection<OsmPrimitive> primitives) {
095        toAdd.clear();
096        toUpdate.clear();
097        toDelete.clear();
098
099        for (OsmPrimitive osm :primitives) {
100            APIOperation op = APIOperation.of(osm);
101            if (op != null) {
102                switch (op) {
103                    case ADD: toAdd.add(osm); break;
104                    case UPDATE: toUpdate.add(osm); break;
105                    case DELETE: toDelete.add(osm); break;
106                    // Used to have a default case for logging: Logging.trace("Ignored primitive {0} -> {1}", osm, op);
107                }
108            }
109        }
110        final Comparator<OsmPrimitive> orderingNodesWaysRelations = OsmPrimitiveComparator.orderingNodesWaysRelations();
111        final Comparator<OsmPrimitive> byUniqueId = OsmPrimitiveComparator.comparingUniqueId();
112        toAdd.sort(orderingNodesWaysRelations.thenComparing(byUniqueId));
113        toUpdate.sort(orderingNodesWaysRelations.thenComparing(byUniqueId));
114        toDelete.sort(orderingNodesWaysRelations.reversed().thenComparing(byUniqueId));
115    }
116
117    /**
118     * initializes the API data set with the modified primitives in <code>ds</code>
119     *
120     * @param ds the data set. Ignored, if null.
121     */
122    public APIDataSet(DataSet ds) {
123        this();
124        init(ds);
125    }
126
127    /**
128     * Replies true if one of the primitives to be updated or to be deleted
129     * participates in at least one conflict in <code>conflicts</code>
130     *
131     * @param conflicts the collection of conflicts
132     * @return true if one of the primitives to be updated or to be deleted
133     * participates in at least one conflict in <code>conflicts</code>
134     */
135    public boolean participatesInConflict(ConflictCollection conflicts) {
136        if (conflicts == null || conflicts.isEmpty()) return false;
137        Set<PrimitiveId> idsParticipatingInConflicts = conflicts.get().stream()
138                .flatMap(c -> Stream.of(c.getMy(), c.getTheir()))
139                .map(OsmPrimitive::getPrimitiveId)
140                .collect(Collectors.toSet());
141        return Stream.of(toUpdate, toDelete)
142                .flatMap(Collection::stream)
143                .map(OsmPrimitive::getPrimitiveId)
144                .anyMatch(idsParticipatingInConflicts::contains);
145    }
146
147    /**
148     * initializes the API data set with the primitives in <code>primitives</code>
149     *
150     * @param primitives the collection of primitives
151     */
152    public APIDataSet(Collection<OsmPrimitive> primitives) {
153        this();
154        init(primitives);
155    }
156
157    /**
158     * Replies true if there are no primitives to upload
159     *
160     * @return true if there are no primitives to upload
161     */
162    public boolean isEmpty() {
163        return toAdd.isEmpty() && toUpdate.isEmpty() && toDelete.isEmpty();
164    }
165
166    /**
167     * Replies the primitives which should be added to the OSM database
168     *
169     * @return the primitives which should be added to the OSM database
170     */
171    public List<OsmPrimitive> getPrimitivesToAdd() {
172        return toAdd;
173    }
174
175    /**
176     * Replies the primitives which should be updated in the OSM database
177     *
178     * @return the primitives which should be updated in the OSM database
179     */
180    public List<OsmPrimitive> getPrimitivesToUpdate() {
181        return toUpdate;
182    }
183
184    /**
185     * Replies the primitives which should be deleted in the OSM database
186     *
187     * @return the primitives which should be deleted in the OSM database
188     */
189    public List<OsmPrimitive> getPrimitivesToDelete() {
190        return toDelete;
191    }
192
193    /**
194     * Replies all primitives
195     *
196     * @return all primitives
197     */
198    public List<OsmPrimitive> getPrimitives() {
199        List<OsmPrimitive> ret = new LinkedList<>();
200        ret.addAll(toAdd);
201        ret.addAll(toUpdate);
202        ret.addAll(toDelete);
203        return ret;
204    }
205
206    /**
207     * Replies the number of objects to upload
208     *
209     * @return the number of objects to upload
210     */
211    public int getSize() {
212        return toAdd.size() + toUpdate.size() + toDelete.size();
213    }
214
215    /**
216     * Removes the given primitives from this {@link APIDataSet}
217     * @param processed The primitives to remove
218     */
219    public void removeProcessed(Collection<IPrimitive> processed) {
220        if (processed == null) return;
221        toAdd.removeAll(processed);
222        toUpdate.removeAll(processed);
223        toDelete.removeAll(processed);
224    }
225
226    /**
227     * Adjusts the upload order for new relations. Child relations are uploaded first,
228     * parent relations second.
229     * <p>
230     * This method detects cyclic dependencies in new relation. Relations with cyclic
231     * dependencies can't be uploaded.
232     *
233     * @throws CyclicUploadDependencyException if a cyclic dependency is detected
234     */
235    public void adjustRelationUploadOrder() throws CyclicUploadDependencyException {
236        List<OsmPrimitive> newToAdd = new LinkedList<>();
237        newToAdd.addAll(Utils.filteredCollection(toAdd, Node.class));
238        newToAdd.addAll(Utils.filteredCollection(toAdd, Way.class));
239
240        List<Relation> relationsToAdd = new ArrayList<>(Utils.filteredCollection(toAdd, Relation.class));
241        List<Relation> noProblemRelations = filterRelationsNotReferringToNewRelations(relationsToAdd);
242        newToAdd.addAll(noProblemRelations);
243        relationsToAdd.removeAll(noProblemRelations);
244
245        RelationUploadDependencyGraph graph = new RelationUploadDependencyGraph(relationsToAdd, true);
246        newToAdd.addAll(graph.computeUploadOrder(false));
247        toAdd = newToAdd;
248
249        List<OsmPrimitive> newToDelete = new LinkedList<>();
250        graph = new RelationUploadDependencyGraph(Utils.filteredCollection(toDelete, Relation.class), false);
251        newToDelete.addAll(graph.computeUploadOrder(true));
252        newToDelete.addAll(Utils.filteredCollection(toDelete, Way.class));
253        newToDelete.addAll(Utils.filteredCollection(toDelete, Node.class));
254        toDelete = newToDelete;
255    }
256
257    /**
258     * Replies the subset of relations in <code>relations</code> which are not referring to any
259     * new relation
260     *
261     * @param relations a list of relations
262     * @return the subset of relations in <code>relations</code> which are not referring to any
263     * new relation
264     */
265    protected List<Relation> filterRelationsNotReferringToNewRelations(Collection<Relation> relations) {
266        List<Relation> ret = new LinkedList<>();
267        for (Relation relation: relations) {
268            boolean refersToNewRelation = relation.getMembers().stream()
269                    .anyMatch(m -> m.isRelation() && m.getMember().isNewOrUndeleted());
270            if (!refersToNewRelation) {
271                ret.add(relation);
272            }
273        }
274        return ret;
275    }
276
277    /**
278     * Utility class to sort a collection of new relations with their dependencies
279     * topologically.
280     *
281     */
282    private static class RelationUploadDependencyGraph {
283        private final Map<Relation, Set<Relation>> children = new HashMap<>();
284        private Collection<Relation> relations;
285        private Set<Relation> visited = new HashSet<>();
286        private List<Relation> uploadOrder;
287        private final boolean newOrUndeleted;
288
289        RelationUploadDependencyGraph(Collection<Relation> relations, boolean newOrUndeleted) {
290            this.newOrUndeleted = newOrUndeleted;
291            build(relations);
292        }
293
294        public final void build(Collection<Relation> relations) {
295            this.relations = new HashSet<>();
296            for (Relation relation: relations) {
297                if (newOrUndeleted ? !relation.isNewOrUndeleted() : !relation.isDeleted()) {
298                    continue;
299                }
300                this.relations.add(relation);
301                for (RelationMember m: relation.getMembers()) {
302                    if (m.isRelation() && (newOrUndeleted ? m.getMember().isNewOrUndeleted() : m.getMember().isDeleted())) {
303                        addDependency(relation, (Relation) m.getMember());
304                    }
305                }
306            }
307        }
308
309        public Set<Relation> getChildren(Relation relation) {
310            return children.computeIfAbsent(relation, k -> new HashSet<>());
311        }
312
313        public void addDependency(Relation relation, Relation child) {
314            getChildren(relation).add(child);
315        }
316
317        protected void visit(Stack<Relation> path, Relation current) throws CyclicUploadDependencyException {
318            if (path.contains(current)) {
319                path.push(current);
320                throw new CyclicUploadDependencyException(path);
321            }
322            if (!visited.contains(current)) {
323                path.push(current);
324                visited.add(current);
325                for (Relation dependent : getChildren(current)) {
326                    visit(path, dependent);
327                }
328                uploadOrder.add(current);
329                path.pop();
330            }
331        }
332
333        public List<Relation> computeUploadOrder(boolean reverse) throws CyclicUploadDependencyException {
334            visited = new HashSet<>();
335            uploadOrder = new LinkedList<>();
336            Stack<Relation> path = new Stack<>();
337            for (Relation relation: relations) {
338                visit(path, relation);
339            }
340            List<Relation> ret = new ArrayList<>(relations);
341            Comparator<? super Relation> cmpr = Comparator.comparingInt(uploadOrder::indexOf);
342            if (reverse) {
343                cmpr = cmpr.reversed();
344            }
345            ret.sort(cmpr);
346            return ret;
347        }
348    }
349}