OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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