OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 20 | Rev 65 | 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.openoffice.spreadsheet.ColumnStyle;
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));
64
        res.add(new Element(ins == XMLVersion.OOo ? "script" : "scripts", ns));
19 ilm 65
        res.add(new Element(OOXML.getLast(ins).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) {
218
        final String family = styleDesc instanceof StyleStyleDesc<?> ? ((StyleStyleDesc<?>) styleDesc).getFamily() : null;
219
        // see section 14.1 § Style Name : "uniquely identifies a style"
220
        // was using an XPath but we had performance issues, we first rewrote it using variables
221
        // (and thus parsing it only once) and saw a 40% speedup, but by rewriting it in java we
222
        // we went from 70ms/instance + 1ms/call to 0.015ms/call :-)
223
        // final String stylePath = "style:style[@style:family=$family and @style:name=$name]";
224
        // this.styleXP = this.getXPath("./office:styles/" + stylePath +
225
        // " | ./office:automatic-styles/" + stylePath +
226
        // " | ./office:master-styles/style:master-page/" + stylePath);
227
        final Element root = this.getDocument().getRootElement();
228
        final Namespace office = getVersion().getOFFICE();
20 ilm 229
        Element res = this.findStyleChild(root.getChild("styles", office), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
17 ilm 230
        if (res != null) {
231
            return res;
232
        }
233
 
20 ilm 234
        res = this.findStyleChild(root.getChild("automatic-styles", office), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
17 ilm 235
        if (res != null) {
236
            return res;
237
        }
238
 
239
        final Element masterStyles = root.getChild("master-styles", office);
240
        if (masterStyles != null) {
20 ilm 241
            res = this.findStyleChild(root.getChild("master-page", getVersion().getSTYLE()), styleDesc.getElementNS(), styleDesc.getElementName(), family, name);
17 ilm 242
            if (res != null) {
243
                return res;
244
            }
245
        }
246
 
247
        return null;
248
    }
249
 
20 ilm 250
    public final Element getDefaultStyle(final StyleStyleDesc<?> styleDesc) {
251
        final Element root = this.getDocument().getRootElement();
252
        final Namespace office = getVersion().getOFFICE();
253
        return this.findStyleChild(root.getChild("styles", office), styleDesc.getElementNS(), StyleStyleDesc.ELEMENT_DEFAULT_NAME, styleDesc.getFamily(), null);
254
    }
255
 
256
    private final Element findStyleChild(final Element styles, final Namespace elemNS, final String elemName, final String family, final String name) {
17 ilm 257
        if (styles == null)
258
            return null;
259
 
260
        final Namespace styleNS = getVersion().getSTYLE();
261
        // from JDOM : traversal through the List is best done with a Iterator
20 ilm 262
        for (final Object o : styles.getChildren(elemName, elemNS)) {
17 ilm 263
            final Element styleElem = (Element) o;
264
            // name first since it is more specific (and often includes family, eg "co2")
20 ilm 265
            if ((name == null || name.equals(styleElem.getAttributeValue("name", styleNS))) && (family == null || family.equals(StyleStyleDesc.getFamily(styleElem)))) {
17 ilm 266
                return styleElem;
267
            }
268
        }
269
        return null;
270
    }
271
 
272
    /**
273
     * Find an unused style name in this document.
274
     *
275
     * @param desc the description of the style, eg {@link ColumnStyle#DESC}.
276
     * @param baseName the base name, eg "myColStyle".
277
     * @return an unused name, eg "myColStyle12".
278
     */
279
    public final String findUnusedName(final StyleDesc<?> desc, final String baseName) {
280
        for (int i = 0; i < 1000; i++) {
281
            final String name = baseName + i;
282
            final Element elem = this.getStyle(desc, name);
283
            if (elem == null)
284
                return name;
285
        }
286
        return null;
287
    }
288
 
289
    public final void addAutoStyle(final Element styleElem) {
290
        this.getChild("automatic-styles", true).addContent(styleElem);
291
    }
292
 
293
    public String asString() {
294
        return JDOMUtils.output(this.content);
295
    }
296
 
297
    protected static interface ElementTransformer {
298
        Element transform(Element elem) throws JDOMException;
299
    }
300
 
301
    protected static final ElementTransformer NOP_ElementTransformer = new ElementTransformer() {
302
        public Element transform(Element elem) {
303
            return elem;
304
        }
305
    };
306
 
307
    protected void mergeAll(ODXMLDocument other, String path) throws JDOMException {
308
        this.mergeAll(other, path, null);
309
    }
310
 
311
    /**
312
     * Fusionne l'élément spécifié par topElem. Applique addTransf avant l'ajout. Attention seuls
313
     * les élément (et non les commentaires, text, etc.) de <code>other</code> sont ajoutés.
314
     *
315
     * @param other le document à fusionner.
316
     * @param path le chemon de l'élément à fusionner, eg "./office:body".
317
     * @param addTransf la transformation à appliquer avant d'ajouter ou <code>null</code>.
318
     * @throws JDOMException
319
     */
320
    protected void mergeAll(ODXMLDocument other, String path, ElementTransformer addTransf) throws JDOMException {
321
        this.add(path, -1, other, path, addTransf);
322
    }
323
 
324
    /**
325
     * Add the part pointed by <code>rpath</code> of other in this document like child number
326
     * <code>lindex</code> of the part pointed by <code>lpath</code>.
327
     *
328
     * @param lpath local xpath.
329
     * @param lindex local index beneath lpath, < 0 meaning the end.
330
     * @param other the document to add.
331
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
332
     *        element itself.
333
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
334
     * @throws JDOMException if an error occur.
335
     */
336
    protected void add(final String lpath, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
337
        this.add(new IFactory<Element>() {
338
            public Element createChecked() {
339
                try {
340
                    return getDescendant(lpath, true);
341
                } catch (JDOMException e) {
342
                    throw new IllegalStateException("error", e);
343
                }
344
            }
345
        }, lindex, other, rpath, addTransf);
346
    }
347
 
348
    /**
349
     * Add the part pointed by <code>rpath</code> of other in this document like child number
350
     * <code>lindex</code> of <code>elem</code>.
351
     *
352
     * @param elem local element, if <code>null</code> add to rpath see
353
     *        {@link #mergeAll(ODXMLDocument, String, org.openconcerto.openoffice.ODXMLDocument.ElementTransformer)}
354
     *        .
355
     * @param lindex local index beneath lpath, < 0 meaning the end, ignored if elem is
356
     *        <code>null</code>.
357
     * @param other the document to add.
358
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
359
     *        element itself.
360
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
361
     * @throws JDOMException if an error occur.
362
     */
363
    protected void add(final Element elem, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
364
        if (elem == null) {
365
            this.mergeAll(other, rpath, addTransf);
366
        } else {
367
            if (!this.getDocument().getRootElement().isAncestor(elem))
368
                throw new IllegalArgumentException(elem + " not part of " + this);
369
            this.add(new IFactory<Element>() {
370
                public Element createChecked() {
371
                    return elem;
372
                }
373
            }, lindex, other, rpath, addTransf);
374
        }
375
    }
376
 
377
    protected final void add(IFactory<Element> elemF, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
378
        final Element toAdd = other.getDescendant(rpath);
379
        // si on a qqchose à ajouter
380
        if (toAdd != null) {
381
            @SuppressWarnings("unchecked")
382
            final List<Content> cloned = toAdd.cloneContent();
383
            final List<Content> listToAdd;
384
            if (addTransf == null) {
385
                listToAdd = cloned;
386
            } else {
387
                listToAdd = new ArrayList<Content>(cloned.size());
19 ilm 388
                final Iterator<Content> iter = cloned.iterator();
17 ilm 389
                while (iter.hasNext()) {
19 ilm 390
                    final Content c = iter.next();
17 ilm 391
                    if (c instanceof Element) {
392
                        final Element transformedElem = addTransf.transform((Element) c);
393
                        if (transformedElem != null)
394
                            listToAdd.add(transformedElem);
395
                    }
396
                }
397
            }
398
            // on crée si besoin le "récepteur"
399
            final Element thisElem = elemF.createChecked();
400
            if (lindex < 0)
401
                thisElem.addContent(listToAdd);
402
            else
403
                thisElem.addContent(lindex, listToAdd);
404
        }
405
    }
406
 
407
    protected final void addIfNotPresent(ODXMLDocument doc, String path) throws JDOMException {
408
        this.addIfNotPresent(doc, path, -1);
409
    }
410
 
411
    /**
412
     * Adds an element from doc to this, if it's not already there.
413
     *
414
     * @param doc the other document.
415
     * @param path an XPath denoting an element, and relative to the root element, eg
416
     *        ./office:settings.
417
     * @param index the index where to add the element, -1 means the end.
418
     * @throws JDOMException if a problem occurs with path.
419
     */
420
    protected final void addIfNotPresent(ODXMLDocument doc, String path, int index) throws JDOMException {
421
        final Element myElem = this.getDescendant(path);
422
        if (myElem == null) {
423
            final Element otherElem = doc.getDescendant(path);
424
            if (otherElem != null) {
425
                final Element myParent = this.getDescendant(XPathUtils.parentOf(path));
426
                if (index == -1)
427
                    myParent.addContent((Element) otherElem.clone());
428
                else
429
                    myParent.addContent(index, (Element) otherElem.clone());
430
            }
431
        }
432
    }
433
 
434
}