OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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