001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.gpx;
003
004import java.util.Objects;
005import java.util.Optional;
006
007import org.openstreetmap.josm.data.gpx.GpxData.XMLNamespace;
008import org.openstreetmap.josm.tools.Utils;
009import org.xml.sax.Attributes;
010
011/**
012 * A GpxExtension that has attributes and child extensions (implements {@link IWithAttributes} and {@link GpxConstants}).
013 * @since 15496
014 */
015public class GpxExtension extends WithAttributes {
016    private final String qualifiedName, prefix, key;
017    private IWithAttributes parent;
018    private String value;
019    private boolean visible = true;
020
021    /**
022     * Constructs a new {@link GpxExtension}.
023     * @param prefix the prefix
024     * @param key the key
025     * @param value the value
026     */
027    public GpxExtension(String prefix, String key, String value) {
028        this.prefix = Optional.ofNullable(prefix).orElse("");
029        this.key = key;
030        this.value = value;
031        this.qualifiedName = (this.prefix.isEmpty() ? "" : this.prefix + ":") + key;
032    }
033
034    /**
035     * Creates a new {@link GpxExtension}
036     *
037     * @param namespaceURI the URI of the XML namespace, used to determine supported extensions
038     *                     (josm, gpxx, gpxd) regardless of the prefix that could legally vary from file to file.
039     * @param qName the qualified name of the XML element including prefix
040     * @param atts the attributes
041     */
042    public GpxExtension(String namespaceURI, String qName, Attributes atts) {
043        qualifiedName = qName;
044        int dot = qName.indexOf(':');
045        String p = findPrefix(namespaceURI);
046        if (p == null) {
047            if (dot != -1) {
048                prefix = qName.substring(0, dot);
049            } else {
050                prefix = "";
051            }
052        } else {
053            prefix = p;
054        }
055        key = qName.substring(dot + 1);
056        for (int i = 0; i < atts.getLength(); i++) {
057            attr.put(atts.getLocalName(i), atts.getValue(i));
058        }
059    }
060
061    /**
062     * Finds the default prefix used by JOSM for the given namespaceURI as the document is free specify another one.
063     * @param namespaceURI namespace URI
064     * @return the prefix
065     */
066    public static String findPrefix(String namespaceURI) {
067        if (XML_URI_EXTENSIONS_DRAWING.equals(namespaceURI))
068            return "gpxd";
069
070        if (XML_URI_EXTENSIONS_GARMIN.equals(namespaceURI))
071            return "gpxx";
072
073        if (XML_URI_EXTENSIONS_JOSM.equals(namespaceURI))
074            return "josm";
075
076        return null;
077    }
078
079    /**
080     * Finds the namespace for the given default prefix, if supported with schema location
081     * @param prefix the prefix used by JOSM
082     * @return the {@link XMLNamespace} element, location and URI can be <code>null</code> if not found.
083     */
084    public static XMLNamespace findNamespace(String prefix) {
085        switch (prefix) {
086        case "gpxx":
087            return new XMLNamespace("gpxx", XML_URI_EXTENSIONS_GARMIN, XML_XSD_EXTENSIONS_GARMIN);
088        case "gpxd":
089            return new XMLNamespace("gpxd", XML_URI_EXTENSIONS_DRAWING, XML_XSD_EXTENSIONS_DRAWING);
090        case "josm":
091            return new XMLNamespace("josm", XML_URI_EXTENSIONS_JOSM, XML_XSD_EXTENSIONS_JOSM);
092        default:
093            return null;
094        }
095    }
096
097    /**
098     * Returns the qualified name of the XML element.
099     * @return the qualified name of the XML element
100     */
101    public String getQualifiedName() {
102        return qualifiedName;
103    }
104
105    /**
106     * Returns the prefix of the XML namespace.
107     * @return the prefix of the XML namespace
108     */
109    public String getPrefix() {
110        return prefix;
111    }
112
113    /**
114     * Returns the key (local element name) of the extension.
115     * @return the key (local element name) of the extension
116     */
117    public String getKey() {
118        return key;
119    }
120
121    /**
122     * Returns the flattened extension key of this extension.
123     * @return the flattened extension key of this extension, used for conversion to OSM layers
124     */
125    public String getFlatKey() {
126        String ret = "";
127        if (parent instanceof GpxExtension) {
128            GpxExtension ext = (GpxExtension) parent;
129            ret = ext.getFlatKey() + ":";
130        }
131        return ret + getKey();
132    }
133
134    /**
135     * Searches recursively for the extension with the given key in all children
136     * @param sPrefix the prefix to look for
137     * @param sKey the key to look for
138     * @return the extension if found, otherwise <code>null</code>
139     */
140    public GpxExtension findExtension(String sPrefix, String sKey) {
141        if (prefix.equalsIgnoreCase(sPrefix) && key.equalsIgnoreCase(sKey)) {
142            return this;
143        } else {
144            return getExtensions().stream()
145                    .map(child -> child.findExtension(sPrefix, sKey))
146                    .filter(Objects::nonNull)
147                    .findFirst().orElse(null);
148        }
149    }
150
151    /**
152     * Returns the value of the extension.
153     * @return the value of the extension
154     */
155    public String getValue() {
156        return value;
157    }
158
159    /**
160     * Sets the value.
161     * @param value the value to set
162     */
163    public void setValue(String value) {
164        this.value = value;
165    }
166
167    /**
168     * Removes this extension from its parent and all then-empty parents
169     * @throws IllegalStateException if parent not set
170     */
171    public void remove() {
172        if (parent == null)
173            throw new IllegalStateException("Extension " + qualifiedName + " has no parent, can't remove it.");
174
175        parent.getExtensions().remove(this);
176        if (parent instanceof GpxExtension) {
177            GpxExtension gpx = ((GpxExtension) parent);
178            if (Utils.isStripEmpty(gpx.getValue())
179                    && Utils.isEmpty(gpx.getAttributes())
180                    && Utils.isEmpty(gpx.getExtensions())) {
181                gpx.remove();
182            }
183        }
184    }
185
186    /**
187     * Hides this extension and all then-empty parents so it isn't written
188     * @see #isVisible()
189     */
190    public void hide() {
191        visible = false;
192        if (parent instanceof GpxExtension) {
193            GpxExtension gpx = (GpxExtension) parent;
194            if (Utils.isStripEmpty(gpx.getValue())
195                    && gpx.getAttributes().isEmpty()
196                    && !gpx.getExtensions().isVisible()) {
197                gpx.hide();
198            }
199        }
200    }
201
202    /**
203     * Shows this extension and all parents so it can be written
204     * @see #isVisible()
205     */
206    public void show() {
207        visible = true;
208        if (parent instanceof GpxExtension) {
209            ((GpxExtension) parent).show();
210        }
211    }
212
213    /**
214     * Determines if this extension should be written.
215     * @return if this extension should be written, used for hiding colors during export without removing them
216     */
217    public boolean isVisible() {
218        return visible;
219    }
220
221    /**
222     * Returns the parent element of this extension.
223     * @return the parent element of this extension, can be another extension or gpx elements (data, track, segment, ...)
224     */
225    public IWithAttributes getParent() {
226        return parent;
227    }
228
229    /**
230     * Sets the parent for this extension
231     * @param parent the parent
232     * @throws IllegalStateException if parent already set
233     */
234    public void setParent(IWithAttributes parent) {
235        if (this.parent != null)
236            throw new IllegalStateException("Parent of extension " + qualifiedName + " is already set");
237
238        this.parent = parent;
239    }
240
241    @Override
242    public int hashCode() {
243        return Objects.hash(prefix, key, value, attr, visible, super.hashCode());
244    }
245
246    @Override
247    public boolean equals(Object obj) {
248        if (this == obj)
249            return true;
250        if (obj == null)
251            return false;
252        if (!super.equals(obj))
253            return false;
254        if (!(obj instanceof GpxExtension))
255            return false;
256        GpxExtension other = (GpxExtension) obj;
257        if (visible != other.visible)
258            return false;
259        if (prefix == null) {
260            if (other.prefix != null)
261                return false;
262        } else if (!prefix.equals(other.prefix))
263            return false;
264        if (key == null) {
265            if (other.key != null)
266                return false;
267        } else if (!key.equals(other.key))
268            return false;
269        if (value == null) {
270            if (other.value != null)
271                return false;
272        } else if (!value.equals(other.value))
273            return false;
274        if (attr == null) {
275            if (other.attr != null)
276                return false;
277        } else if (!attr.equals(other.attr))
278            return false;
279        return true;
280    }
281}