OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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