OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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