OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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