OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
185 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
17 ilm 5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 /*
15
 * Créé le 28 oct. 2004
16
 */
17
package org.openconcerto.openoffice;
18
 
25 ilm 19
import org.openconcerto.openoffice.ODPackage.RootElement;
180 ilm 20
import org.openconcerto.utils.cache.LRUMap;
17 ilm 21
import org.openconcerto.utils.cc.IFactory;
22
import org.openconcerto.xml.JDOMUtils;
23
import org.openconcerto.xml.Validator;
24
import org.openconcerto.xml.XPathUtils;
25
 
26
import java.util.ArrayList;
27
import java.util.Collections;
28
import java.util.HashMap;
29
import java.util.Iterator;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Set;
33
 
34
import org.jdom.Content;
35
import org.jdom.Document;
36
import org.jdom.Element;
37
import org.jdom.JDOMException;
38
import org.jdom.Namespace;
39
import org.jdom.xpath.XPath;
40
 
41
/**
42
 * An OpenDocument XML document, like content.xml ou styles.xml.
43
 *
44
 * @author Sylvain CUAZ
45
 */
46
public class ODXMLDocument {
47
 
48
    /**
49
     * All top-level elements that an office document may contain. Note that only the single xml
50
     * representation (office:document) contains all of them.
51
     */
52
    private static final Map<XMLVersion, List<Element>> ELEMS_ORDER;
53
    static {
54
        ELEMS_ORDER = new HashMap<XMLVersion, List<Element>>(2);
55
        ELEMS_ORDER.put(XMLVersion.getOOo(), createChildren(XMLVersion.getOOo()));
56
        ELEMS_ORDER.put(XMLVersion.getOD(), createChildren(XMLVersion.getOD()));
57
    }
58
 
59
    private static final List<Element> createChildren(XMLVersion ins) {
60
        final Namespace ns = ins.getOFFICE();
61
        final List<Element> res = new ArrayList<Element>(8);
62
        res.add(new Element("meta", ns));
63
        res.add(new Element("settings", ns));
73 ilm 64
        final OOXML xml = OOXML.getLast(ins);
65
        res.add(new Element(xml.getOfficeScripts(), ns));
66
        res.add(new Element(xml.getFontDecls()[0], ns));
17 ilm 67
        res.add(new Element("styles", ns));
68
        res.add(new Element("automatic-styles", ns));
69
        res.add(new Element("master-styles", ns));
70
        res.add(new Element("body", ns));
71
        return res;
72
    }
73
 
83 ilm 74
    static private final int ITERATIONS_WARNING_COUNT = 2000;
17 ilm 75
    // namespaces for the name attributes
76
    static private final Map<String, String> namePrefixes;
77
    static {
78
        namePrefixes = new HashMap<String, String>();
79
        namePrefixes.put("table:table", "table");
80
        namePrefixes.put("text:a", "office");
81
        namePrefixes.put("draw:text-box", "draw");
82
        namePrefixes.put("draw:image", "draw");
83
        namePrefixes.put("draw:frame", "draw");
84
    }
85
 
86
    /**
87
     * The XML elements posessing a name.
88
     *
89
     * @return the qualified names of named elements.
90
     * @see #getDescendantByName(String, String)
91
     */
92
    public static Set<String> getNamedElements() {
93
        return Collections.unmodifiableSet(namePrefixes.keySet());
94
    }
95
 
25 ilm 96
    public static final ODXMLDocument create(final Document doc) {
97
        if (RootElement.fromDocument(doc) == RootElement.SINGLE_CONTENT)
98
            return new ODSingleXMLDocument(doc);
99
        else
100
            return new ODXMLDocument(doc);
101
    }
102
 
17 ilm 103
    private final Document content;
19 ilm 104
    private final XMLFormatVersion version;
17 ilm 105
    private final ChildCreator childCreator;
83 ilm 106
    private final Map<String, Integer> styleNamesLast;
17 ilm 107
 
108
    // before making it public, assure that content is really of version "version"
109
    // eg by checking some namespace
19 ilm 110
    protected ODXMLDocument(final Document content, final XMLFormatVersion version) {
17 ilm 111
        if (content == null)
112
            throw new NullPointerException("null document");
113
        this.content = content;
114
        this.version = version;
115
        this.childCreator = new ChildCreator(this.content.getRootElement(), ELEMS_ORDER.get(this.getVersion()));
180 ilm 116
        this.styleNamesLast = new LRUMap<>(15, 4);
17 ilm 117
    }
118
 
119
    public ODXMLDocument(Document content) {
19 ilm 120
        this(content, XMLFormatVersion.get(content.getRootElement()));
17 ilm 121
    }
122
 
123
    public ODXMLDocument(ODXMLDocument doc) {
124
        this((Document) doc.content.clone(), doc.version);
125
    }
126
 
127
    public Document getDocument() {
128
        return this.content;
129
    }
130
 
131
    public Validator getValidator() {
19 ilm 132
        return getXML().getValidator(this.getDocument());
17 ilm 133
    }
134
 
19 ilm 135
    public final OOXML getXML() {
136
        return this.getFormatVersion().getXML();
137
    }
138
 
139
    public final XMLFormatVersion getFormatVersion() {
17 ilm 140
        return this.version;
141
    }
142
 
19 ilm 143
    public final XMLVersion getVersion() {
144
        return this.getFormatVersion().getXMLVersion();
145
    }
146
 
17 ilm 147
    // *** children
148
 
149
    public final Element getChild(String childName) {
150
        return this.getChild(childName, false);
151
    }
152
 
153
    /**
154
     * Return the asked child, optionally creating it.
155
     *
156
     * @param childName the name of the child.
157
     * @param create whether it should be created in case it doesn't exist.
158
     * @return the asked child or <code>null</code> if it doesn't exist and create is
159
     *         <code>false</code>
160
     */
161
    public Element getChild(String childName, boolean create) {
162
        return this.childCreator.getChild(this.getVersion().getOFFICE(), childName, create);
163
    }
164
 
165
    public void setChild(Element elem) {
166
        if (!elem.getNamespace().equals(this.getVersion().getOFFICE()))
167
            throw new IllegalArgumentException("all children of a document belong to the office namespace.");
168
        this.childCreator.setChild(elem);
169
    }
170
 
171
    // *** descendants
172
 
173
    protected final Element getDescendant(String path) throws JDOMException {
174
        return this.getDescendant(path, false);
175
    }
176
 
177
    protected final Element getDescendant(String path, boolean create) throws JDOMException {
178
        Element res = (Element) this.getXPath(path).selectSingleNode(this.getDocument().getRootElement());
179
        if (res == null && create) {
180
            final Element parent = this.getDescendant(XPathUtils.parentOf(path), create);
181
            final String namespace = XPathUtils.namespace(path);
182
            final Namespace ns = namespace == null ? null : this.getVersion().getNS(namespace);
183
            res = new Element(XPathUtils.localName(path), ns);
184
            parent.addContent(res);
185
        }
186
        return res;
187
    }
188
 
189
    public final XPath getXPath(String string) throws JDOMException {
190
        return OOUtils.getXPath(string, this.getVersion());
191
    }
192
 
193
    /**
194
     * Search for a descendant with the passed name.
195
     *
196
     * @param qName the XML element qualified name, eg "table:table".
197
     * @param name the value of the name, eg "MyTable".
198
     * @return the first element named <code>name</code> or <code>null</code> if none is found, eg
199
     *         &lt;table:table table:name="MyTable" &gt;
200
     * @throws IllegalArgumentException if <code>qName</code> is not in {@link #getNamedElements()}
201
     */
202
    public final Element getDescendantByName(String qName, String name) {
203
        return this.getDescendantByName(this.getDocument().getRootElement(), qName, name);
204
    }
205
 
206
    public final Element getDescendantByName(Element root, String qName, String name) {
207
        if (root.getDocument() != this.getDocument())
208
            throw new IllegalArgumentException("root is not part of this.");
209
        if (!namePrefixes.containsKey(qName))
210
            throw new IllegalArgumentException(qName + " not in " + getNamedElements());
211
        final String xp = ".//" + qName + "[@" + namePrefixes.get(qName) + ":name='" + name + "']";
212
        try {
213
            return (Element) this.getXPath(xp).selectSingleNode(root);
214
        } catch (JDOMException e) {
215
            // static xpath, should not happen
216
            throw new IllegalStateException("could not find " + xp, e);
217
        }
218
    }
219
 
220
    // *** styles
221
    public final Element getStyle(final StyleDesc<?> styleDesc, final String name) {
73 ilm 222
        return this.getStyle(styleDesc, name, this.getDocument());
223
    }
224
 
225
    public final Element getStyle(final StyleDesc<?> styleDesc, final String name, final Document referent) {
17 ilm 226
        final String family = styleDesc instanceof StyleStyleDesc<?> ? ((StyleStyleDesc<?>) styleDesc).getFamily() : null;
227
        // see section 14.1 § Style Name : "uniquely identifies a style"
228
        // was using an XPath but we had performance issues, we first rewrote it using variables
229
        // (and thus parsing it only once) and saw a 40% speedup, but by rewriting it in java we
230
        // we went from 70ms/instance + 1ms/call to 0.015ms/call :-)
231
        // final String stylePath = "style:style[@style:family=$family and @style:name=$name]";
232
        // this.styleXP = this.getXPath("./office:styles/" + stylePath +
233
        // " | ./office:automatic-styles/" + stylePath +
234
        // " | ./office:master-styles/style:master-page/" + stylePath);
235
        final Element root = this.getDocument().getRootElement();
236
        final Namespace office = getVersion().getOFFICE();
20 ilm 237
        Element res = this.findStyleChild(root.getChild("styles", office), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
17 ilm 238
        if (res != null) {
239
            return res;
240
        }
241
 
73 ilm 242
        // automatic-styles are only reachable from the same document
243
        if (referent == this.getDocument()) {
244
            res = this.findStyleChild(root.getChild("automatic-styles", office), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
245
            if (res != null) {
246
                return res;
247
            }
17 ilm 248
        }
249
 
250
        final Element masterStyles = root.getChild("master-styles", office);
251
        if (masterStyles != null) {
20 ilm 252
            res = this.findStyleChild(root.getChild("master-page", getVersion().getSTYLE()), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
17 ilm 253
            if (res != null) {
254
                return res;
255
            }
256
        }
257
 
258
        return null;
259
    }
260
 
65 ilm 261
    public final Element getDefaultStyle(final StyleStyleDesc<?> styleDesc, final boolean create) {
262
        final Element stylesElem = this.getChild("styles", create);
263
        final Element res = this.findStyleChild(stylesElem, styleDesc.getElementNS(), StyleStyleDesc.ELEMENT_DEFAULT_NAME, styleDesc.getFamily(), null);
264
        if (res != null || !create) {
265
            return res;
266
        } else {
267
            final Element created = styleDesc.createDefaultElement();
268
            // OK to add at the end, the relaxNG for office:styles is 'interleave'
269
            stylesElem.addContent(created);
270
            return created;
271
        }
20 ilm 272
    }
273
 
274
    private final Element findStyleChild(final Element styles, final Namespace elemNS, final String elemName, final String family, final String name) {
17 ilm 275
        if (styles == null)
276
            return null;
277
 
278
        final Namespace styleNS = getVersion().getSTYLE();
279
        // from JDOM : traversal through the List is best done with a Iterator
20 ilm 280
        for (final Object o : styles.getChildren(elemName, elemNS)) {
17 ilm 281
            final Element styleElem = (Element) o;
282
            // name first since it is more specific (and often includes family, eg "co2")
20 ilm 283
            if ((name == null || name.equals(styleElem.getAttributeValue("name", styleNS))) && (family == null || family.equals(StyleStyleDesc.getFamily(styleElem)))) {
17 ilm 284
                return styleElem;
285
            }
286
        }
287
        return null;
288
    }
289
 
290
    /**
291
     * Find an unused style name in this document.
292
     *
65 ilm 293
     * @param desc the description of the style.
294
     * @param baseName the base name, e.g. "myColStyle".
295
     * @return an unused name, e.g. "myColStyle12".
296
     * @see Style#getStyleDesc(Class, XMLVersion)
17 ilm 297
     */
298
    public final String findUnusedName(final StyleDesc<?> desc, final String baseName) {
83 ilm 299
        final Integer lastI = this.styleNamesLast.get(baseName);
300
        final int offset = lastI == null ? 0 : lastI.intValue();
301
        int iterationCount = 0;
302
        int i = offset;
303
        String res = null;
304
        while (res == null) {
17 ilm 305
            final String name = baseName + i;
306
            final Element elem = this.getStyle(desc, name);
83 ilm 307
            iterationCount++;
308
            // don't increment i if we succeed since we don't know if the found name will indeed be
309
            // used
310
            if (elem == null) {
311
                res = name;
312
            } else {
313
                i++;
314
                // warn early before it takes too long
315
                if (iterationCount == ITERATIONS_WARNING_COUNT) {
316
                    Log.get().warning("After " + iterationCount + " iterations, no unused name found for " + baseName + " (" + desc + ")");
317
                }
318
            }
17 ilm 319
        }
83 ilm 320
        this.styleNamesLast.put(baseName, i);
321
        if (iterationCount >= ITERATIONS_WARNING_COUNT) {
322
            // MAYBE trigger an optimize pass that merges equal styles.
323
            Log.get().warning(iterationCount + " iterations were needed to find an unused name for " + baseName + " (" + desc + ")");
324
        }
325
        return res;
17 ilm 326
    }
327
 
83 ilm 328
    // Useful if many styles are removed (to avoid "ce12345")
329
    final void clearStyleNameCache() {
330
        this.styleNamesLast.clear();
331
    }
332
 
17 ilm 333
    public final void addAutoStyle(final Element styleElem) {
334
        this.getChild("automatic-styles", true).addContent(styleElem);
335
    }
336
 
337
    public String asString() {
338
        return JDOMUtils.output(this.content);
339
    }
340
 
341
    protected static interface ElementTransformer {
342
        Element transform(Element elem) throws JDOMException;
343
    }
344
 
345
    protected static final ElementTransformer NOP_ElementTransformer = new ElementTransformer() {
346
        public Element transform(Element elem) {
347
            return elem;
348
        }
349
    };
350
 
351
    protected void mergeAll(ODXMLDocument other, String path) throws JDOMException {
352
        this.mergeAll(other, path, null);
353
    }
354
 
355
    /**
356
     * Fusionne l'élément spécifié par topElem. Applique addTransf avant l'ajout. Attention seuls
357
     * les élément (et non les commentaires, text, etc.) de <code>other</code> sont ajoutés.
358
     *
359
     * @param other le document à fusionner.
360
     * @param path le chemon de l'élément à fusionner, eg "./office:body".
361
     * @param addTransf la transformation à appliquer avant d'ajouter ou <code>null</code>.
362
     * @throws JDOMException
363
     */
364
    protected void mergeAll(ODXMLDocument other, String path, ElementTransformer addTransf) throws JDOMException {
365
        this.add(path, -1, other, path, addTransf);
366
    }
367
 
368
    /**
369
     * Add the part pointed by <code>rpath</code> of other in this document like child number
370
     * <code>lindex</code> of the part pointed by <code>lpath</code>.
371
     *
372
     * @param lpath local xpath.
373
     * @param lindex local index beneath lpath, < 0 meaning the end.
374
     * @param other the document to add.
375
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
376
     *        element itself.
377
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
378
     * @throws JDOMException if an error occur.
379
     */
380
    protected void add(final String lpath, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
381
        this.add(new IFactory<Element>() {
382
            public Element createChecked() {
383
                try {
384
                    return getDescendant(lpath, true);
385
                } catch (JDOMException e) {
386
                    throw new IllegalStateException("error", e);
387
                }
388
            }
389
        }, lindex, other, rpath, addTransf);
390
    }
391
 
392
    /**
393
     * Add the part pointed by <code>rpath</code> of other in this document like child number
394
     * <code>lindex</code> of <code>elem</code>.
395
     *
396
     * @param elem local element, if <code>null</code> add to rpath see
397
     *        {@link #mergeAll(ODXMLDocument, String, org.openconcerto.openoffice.ODXMLDocument.ElementTransformer)}
398
     *        .
399
     * @param lindex local index beneath lpath, < 0 meaning the end, ignored if elem is
400
     *        <code>null</code>.
401
     * @param other the document to add.
402
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
403
     *        element itself.
404
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
405
     * @throws JDOMException if an error occur.
406
     */
407
    protected void add(final Element elem, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
408
        if (elem == null) {
409
            this.mergeAll(other, rpath, addTransf);
410
        } else {
411
            if (!this.getDocument().getRootElement().isAncestor(elem))
412
                throw new IllegalArgumentException(elem + " not part of " + this);
413
            this.add(new IFactory<Element>() {
414
                public Element createChecked() {
415
                    return elem;
416
                }
417
            }, lindex, other, rpath, addTransf);
418
        }
419
    }
420
 
421
    protected final void add(IFactory<Element> elemF, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
422
        final Element toAdd = other.getDescendant(rpath);
423
        // si on a qqchose à ajouter
424
        if (toAdd != null) {
425
            @SuppressWarnings("unchecked")
426
            final List<Content> cloned = toAdd.cloneContent();
427
            final List<Content> listToAdd;
428
            if (addTransf == null) {
429
                listToAdd = cloned;
430
            } else {
431
                listToAdd = new ArrayList<Content>(cloned.size());
19 ilm 432
                final Iterator<Content> iter = cloned.iterator();
17 ilm 433
                while (iter.hasNext()) {
19 ilm 434
                    final Content c = iter.next();
17 ilm 435
                    if (c instanceof Element) {
436
                        final Element transformedElem = addTransf.transform((Element) c);
437
                        if (transformedElem != null)
438
                            listToAdd.add(transformedElem);
73 ilm 439
                    } else {
440
                        // keep non element as when addTransf is null
441
                        // perhaps use a Transformer<Content> to allow to remove or modify
442
                        listToAdd.add(c);
17 ilm 443
                    }
444
                }
445
            }
446
            // on crée si besoin le "récepteur"
447
            final Element thisElem = elemF.createChecked();
448
            if (lindex < 0)
449
                thisElem.addContent(listToAdd);
450
            else
451
                thisElem.addContent(lindex, listToAdd);
452
        }
453
    }
454
 
455
    protected final void addIfNotPresent(ODXMLDocument doc, String path) throws JDOMException {
456
        this.addIfNotPresent(doc, path, -1);
457
    }
458
 
459
    /**
460
     * Adds an element from doc to this, if it's not already there.
461
     *
462
     * @param doc the other document.
463
     * @param path an XPath denoting an element, and relative to the root element, eg
464
     *        ./office:settings.
465
     * @param index the index where to add the element, -1 means the end.
466
     * @throws JDOMException if a problem occurs with path.
467
     */
468
    protected final void addIfNotPresent(ODXMLDocument doc, String path, int index) throws JDOMException {
469
        final Element myElem = this.getDescendant(path);
470
        if (myElem == null) {
471
            final Element otherElem = doc.getDescendant(path);
472
            if (otherElem != null) {
473
                final Element myParent = this.getDescendant(XPathUtils.parentOf(path));
474
                if (index == -1)
475
                    myParent.addContent((Element) otherElem.clone());
476
                else
477
                    myParent.addContent(index, (Element) otherElem.clone());
478
            }
479
        }
480
    }
481
 
482
}