~ubuntu-branches/ubuntu/precise/kompozer/precise

« back to all changes in this revision

Viewing changes to mozilla/extensions/transformiix/source/xslt/txStandaloneXSLTProcessor.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Anthony Yarusso
  • Date: 2007-08-27 01:11:03 UTC
  • Revision ID: james.westby@ubuntu.com-20070827011103-2jgf4s6532gqu2ka
Tags: upstream-0.7.10
ImportĀ upstreamĀ versionĀ 0.7.10

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 
2
/* ***** BEGIN LICENSE BLOCK *****
 
3
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
4
 *
 
5
 * The contents of this file are subject to the Mozilla Public License Version
 
6
 * 1.1 (the "License"); you may not use this file except in compliance with
 
7
 * the License. You may obtain a copy of the License at
 
8
 * http://www.mozilla.org/MPL/
 
9
 *
 
10
 * Software distributed under the License is distributed on an "AS IS" basis,
 
11
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 
12
 * for the specific language governing rights and limitations under the
 
13
 * License.
 
14
 *
 
15
 * The Original Code is mozilla.org code.
 
16
 *
 
17
 * The Initial Developer of the Original Code is
 
18
 * Netscape Communications Corporation.
 
19
 * Portions created by the Initial Developer are Copyright (C) 2002
 
20
 * the Initial Developer. All Rights Reserved.
 
21
 *
 
22
 * Contributor(s):
 
23
 *   Peter Van der Beken <peterv@netscape.com> (original author)
 
24
 *   Axel Hecht <axel@pike.org>
 
25
 *
 
26
 *
 
27
 * Alternatively, the contents of this file may be used under the terms of
 
28
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 
29
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 
30
 * in which case the provisions of the GPL or the LGPL are applicable instead
 
31
 * of those above. If you wish to allow use of your version of this file only
 
32
 * under the terms of either the GPL or the LGPL, and not to allow others to
 
33
 * use your version of this file under the terms of the MPL, indicate your
 
34
 * decision by deleting the provisions above and replace them with the notice
 
35
 * and other provisions required by the GPL or the LGPL. If you do not delete
 
36
 * the provisions above, a recipient may use your version of this file under
 
37
 * the terms of any one of the MPL, the GPL or the LGPL.
 
38
 *
 
39
 * ***** END LICENSE BLOCK ***** */
 
40
 
 
41
#include "txStandaloneXSLTProcessor.h"
 
42
#include "txStandaloneStylesheetCompiler.h"
 
43
#include "nsCRT.h"
 
44
#include "nsReadableUtils.h"
 
45
#include "txHTMLOutput.h"
 
46
#include "txTextOutput.h"
 
47
#include "txUnknownHandler.h"
 
48
#include "txURIUtils.h"
 
49
#include "txXMLParser.h"
 
50
 
 
51
TX_IMPL_DOM_STATICS;
 
52
 
 
53
/**
 
54
 * Output Handler Factory
 
55
 */
 
56
class txStandaloneHandlerFactory : public txAOutputHandlerFactory
 
57
{
 
58
public:
 
59
    txStandaloneHandlerFactory(txExecutionState* aEs,
 
60
                               ostream* aStream)
 
61
        : mEs(aEs), mStream(aStream)
 
62
    {
 
63
    }
 
64
 
 
65
    virtual ~txStandaloneHandlerFactory()
 
66
    {
 
67
    };
 
68
 
 
69
    TX_DECL_TXAOUTPUTHANDLERFACTORY;
 
70
 
 
71
private:
 
72
    txExecutionState* mEs;
 
73
    ostream* mStream;
 
74
};
 
75
 
 
76
nsresult
 
77
txStandaloneHandlerFactory::createHandlerWith(txOutputFormat* aFormat,
 
78
                                              txAOutputXMLEventHandler** aHandler)
 
79
{
 
80
    *aHandler = 0;
 
81
    switch (aFormat->mMethod) {
 
82
        case eXMLOutput:
 
83
            *aHandler = new txXMLOutput(aFormat, mStream);
 
84
            break;
 
85
 
 
86
        case eHTMLOutput:
 
87
            *aHandler = new txHTMLOutput(aFormat, mStream);
 
88
            break;
 
89
 
 
90
        case eTextOutput:
 
91
            *aHandler = new txTextOutput(mStream);
 
92
            break;
 
93
 
 
94
        case eMethodNotSet:
 
95
            *aHandler = new txUnknownHandler(mEs);
 
96
            break;
 
97
    }
 
98
    NS_ENSURE_TRUE(*aHandler, NS_ERROR_OUT_OF_MEMORY);
 
99
    return NS_OK;
 
100
}
 
101
 
 
102
nsresult
 
103
txStandaloneHandlerFactory::createHandlerWith(txOutputFormat* aFormat,
 
104
                                              const nsAString& aName,
 
105
                                              PRInt32 aNsID,
 
106
                                              txAOutputXMLEventHandler** aHandler)
 
107
{
 
108
    *aHandler = 0;
 
109
    NS_ASSERTION(aFormat->mMethod != eMethodNotSet,
 
110
                 "How can method not be known when root element is?");
 
111
    NS_ENSURE_TRUE(aFormat->mMethod != eMethodNotSet, NS_ERROR_UNEXPECTED);
 
112
    return createHandlerWith(aFormat, aHandler);
 
113
}
 
114
 
 
115
 
 
116
/**
 
117
 * txStandaloneXSLTProcessor
 
118
 */
 
119
 
 
120
/**
 
121
 * Transform a XML document given by path.
 
122
 * The stylesheet is retrieved by a processing instruction,
 
123
 * or an error is returned.
 
124
 */
 
125
nsresult
 
126
txStandaloneXSLTProcessor::transform(nsACString& aXMLPath, ostream& aOut,
 
127
                                     ErrorObserver& aErr)
 
128
{
 
129
    txXPathNode* xmlDoc = parsePath(aXMLPath, aErr);
 
130
    if (!xmlDoc) {
 
131
        return NS_ERROR_FAILURE;
 
132
    }
 
133
 
 
134
    // transform
 
135
    nsresult rv = transform(*xmlDoc, aOut, aErr);
 
136
 
 
137
    delete xmlDoc;
 
138
 
 
139
    return rv;
 
140
}
 
141
 
 
142
/**
 
143
 * Transform a XML document given by path with the given
 
144
 * stylesheet.
 
145
 */
 
146
nsresult
 
147
txStandaloneXSLTProcessor::transform(nsACString& aXMLPath,
 
148
                                     nsACString& aXSLPath, ostream& aOut,
 
149
                                     ErrorObserver& aErr)
 
150
{
 
151
    txXPathNode* xmlDoc = parsePath(aXMLPath, aErr);
 
152
    if (!xmlDoc) {
 
153
        return NS_ERROR_FAILURE;
 
154
    }
 
155
    txParsedURL path;
 
156
    path.init(NS_ConvertASCIItoUCS2(aXSLPath));
 
157
    nsRefPtr<txStylesheet> style;
 
158
    nsresult rv = TX_CompileStylesheetPath(path, getter_AddRefs(style));
 
159
    if (NS_FAILED(rv)) {
 
160
        delete xmlDoc;
 
161
        return rv;
 
162
    }
 
163
    // transform
 
164
    rv = transform(*xmlDoc, style, aOut, aErr);
 
165
 
 
166
    delete xmlDoc;
 
167
 
 
168
    return rv;
 
169
}
 
170
 
 
171
/**
 
172
 * Transform a XML document.
 
173
 * The stylesheet is retrieved by a processing instruction,
 
174
 * or an error is returned.
 
175
 */
 
176
nsresult
 
177
txStandaloneXSLTProcessor::transform(txXPathNode& aXMLDoc, ostream& aOut,
 
178
                                     ErrorObserver& aErr)
 
179
{
 
180
    Document* xmlDoc;
 
181
    nsresult rv = txXPathNativeNode::getDocument(aXMLDoc, &xmlDoc);
 
182
    NS_ENSURE_SUCCESS(rv, rv);
 
183
 
 
184
    // get stylesheet path
 
185
    nsAutoString stylePath, basePath;
 
186
    xmlDoc->getBaseURI(basePath);
 
187
    getHrefFromStylesheetPI(*xmlDoc, stylePath);
 
188
    txParsedURL base, ref, resolved;
 
189
    base.init(basePath);
 
190
    ref.init(stylePath);
 
191
    base.resolve(ref, resolved);
 
192
 
 
193
    nsRefPtr<txStylesheet> style;
 
194
    rv = TX_CompileStylesheetPath(resolved, getter_AddRefs(style));
 
195
    NS_ENSURE_SUCCESS(rv, rv);
 
196
 
 
197
    // transform
 
198
    rv = transform(aXMLDoc, style, aOut, aErr);
 
199
 
 
200
    return rv;
 
201
}
 
202
 
 
203
/**
 
204
 * Processes the given XML Document using the given XSL document
 
205
 * and prints the results to the given ostream argument
 
206
 */
 
207
nsresult
 
208
txStandaloneXSLTProcessor::transform(txXPathNode& aSource,
 
209
                                     txStylesheet* aStylesheet,
 
210
                                     ostream& aOut, ErrorObserver& aErr)
 
211
{
 
212
    // Create a new txEvalState
 
213
    txExecutionState es(aStylesheet);
 
214
 
 
215
    // XXX todo es.addErrorObserver(aErr);
 
216
 
 
217
    txStandaloneHandlerFactory handlerFactory(&es, &aOut);
 
218
 
 
219
#ifndef XP_WIN
 
220
    bool sync = aOut.sync_with_stdio(false);
 
221
#endif
 
222
    es.mOutputHandlerFactory = &handlerFactory;
 
223
 
 
224
    es.init(aSource, nsnull);
 
225
 
 
226
    // Process root of XML source document
 
227
    nsresult rv = txXSLTProcessor::execute(es);
 
228
    es.end();
 
229
 
 
230
#ifndef XP_WIN
 
231
    aOut.sync_with_stdio(sync);
 
232
#endif
 
233
 
 
234
    return rv;
 
235
}
 
236
 
 
237
/**
 
238
 * Parses the XML Stylesheet PIs associated with the
 
239
 * given XML document. If a stylesheet PIs is found with type="text/xsl"
 
240
 * or type="text/xml" the href psuedo attribute value will be appended to
 
241
 * the given href argument. If multiple text/xsl stylesheet PIs
 
242
 * are found, the first one is used.
 
243
 */
 
244
void txStandaloneXSLTProcessor::getHrefFromStylesheetPI(Document& xmlDocument,
 
245
                                                        nsAString& href)
 
246
{
 
247
    Node* node = xmlDocument.getFirstChild();
 
248
    nsAutoString type;
 
249
    nsAutoString tmpHref;
 
250
    while (node) {
 
251
        if (node->getNodeType() == Node::PROCESSING_INSTRUCTION_NODE) {
 
252
            nsAutoString target;
 
253
            node->getNodeName(target);
 
254
            if (target.Equals(NS_LITERAL_STRING("xml-stylesheet"))) {
 
255
                nsAutoString data;
 
256
                node->getNodeValue(data);
 
257
                type.Truncate();
 
258
                tmpHref.Truncate();
 
259
                parseStylesheetPI(data, type, tmpHref);
 
260
                if (type.Equals(NS_LITERAL_STRING("text/xsl")) ||
 
261
                    type.Equals(NS_LITERAL_STRING("text/xml"))) {
 
262
                    href = tmpHref;
 
263
                    return;
 
264
                }
 
265
            }
 
266
        }
 
267
        node = node->getNextSibling();
 
268
    }
 
269
}
 
270
 
 
271
/**
 
272
 * Parses the contents of data, and returns the type and href pseudo attributes
 
273
 * (Based on code copied from nsParserUtils)
 
274
 */
 
275
#define SKIP_WHITESPACE(iter, end_iter)                          \
 
276
  while ((iter) != (end_iter) && nsCRT::IsAsciiSpace(*(iter))) { \
 
277
    ++(iter);                                                    \
 
278
  }                                                              \
 
279
  if ((iter) == (end_iter))                                      \
 
280
    break
 
281
 
 
282
#define SKIP_ATTR_NAME(iter, end_iter)                            \
 
283
  while ((iter) != (end_iter) && !nsCRT::IsAsciiSpace(*(iter)) && \
 
284
         *(iter) != '=') {                                        \
 
285
    ++(iter);                                                     \
 
286
  }                                                               \
 
287
  if ((iter) == (end_iter))                                       \
 
288
    break
 
289
 
 
290
void txStandaloneXSLTProcessor::parseStylesheetPI(const nsAFlatString& aData,
 
291
                                                  nsAString& aType,
 
292
                                                  nsAString& aHref)
 
293
{
 
294
  nsAFlatString::const_char_iterator start, end;
 
295
  aData.BeginReading(start);
 
296
  aData.EndReading(end);
 
297
  nsAFlatString::const_char_iterator iter;
 
298
  PRInt8 found = 0;
 
299
 
 
300
  while (start != end) {
 
301
    SKIP_WHITESPACE(start, end);
 
302
    iter = start;
 
303
    SKIP_ATTR_NAME(iter, end);
 
304
 
 
305
    // Remember the attr name.
 
306
    const nsAString & attrName = Substring(start, iter);
 
307
 
 
308
    // Now check whether this is a valid name="value" pair.
 
309
    start = iter;
 
310
    SKIP_WHITESPACE(start, end);
 
311
    if (*start != '=') {
 
312
      // No '=', so this is not a name="value" pair.  We don't know
 
313
      // what it is, and we have no way to handle it.
 
314
      break;
 
315
    }
 
316
 
 
317
    // Have to skip the value.
 
318
    ++start;
 
319
    SKIP_WHITESPACE(start, end);
 
320
    PRUnichar q = *start;
 
321
    if (q != QUOTE && q != APOSTROPHE) {
 
322
      // Not a valid quoted value, so bail.
 
323
      break;
 
324
    }
 
325
 
 
326
    ++start;  // Point to the first char of the value.
 
327
    iter = start;
 
328
    while (iter != end && *iter != q) {
 
329
      ++iter;
 
330
    }
 
331
    if (iter == end) {
 
332
      // Oops, unterminated quoted string.
 
333
      break;
 
334
    }
 
335
    
 
336
    // At this point attrName holds the name of the "attribute" and
 
337
    // the value is between start and iter.
 
338
    if (attrName.Equals(NS_LITERAL_STRING("type"))) {
 
339
      aType = Substring(start, iter);
 
340
      ++found;
 
341
    }
 
342
    else if (attrName.Equals(NS_LITERAL_STRING("href"))) {
 
343
      aHref = Substring(start, iter);
 
344
      ++found;
 
345
    }
 
346
 
 
347
    // Stop if we found both attributes
 
348
    if (found == 2) {
 
349
      break;
 
350
    }
 
351
 
 
352
    // Resume scanning after the end of the attribute value.
 
353
    start = iter;
 
354
    ++start;  // To move past the quote char.
 
355
  }
 
356
}
 
357
 
 
358
txXPathNode*
 
359
txStandaloneXSLTProcessor::parsePath(const nsACString& aPath, ErrorObserver& aErr)
 
360
{
 
361
    NS_ConvertASCIItoUCS2 path(aPath);
 
362
 
 
363
    ifstream xmlInput(PromiseFlatCString(aPath).get(), ios::in);
 
364
    if (!xmlInput) {
 
365
        aErr.receiveError(NS_LITERAL_STRING("Couldn't open ") + path);
 
366
        return 0;
 
367
    }
 
368
    // parse source
 
369
    txXPathNode* xmlDoc;
 
370
    nsAutoString errors;
 
371
    nsresult rv = txParseFromStream(xmlInput, path, errors, &xmlDoc);
 
372
    xmlInput.close();
 
373
    if (NS_FAILED(rv) || !xmlDoc) {
 
374
        aErr.receiveError(NS_LITERAL_STRING("Parsing error \"") + errors +
 
375
                          NS_LITERAL_STRING("\""));
 
376
    }
 
377
    return xmlDoc;
 
378
}