View | Details | Raw Unified | Return to bug 33030
Collapse All | Expand All

(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XPointerFactory.java (-332 lines)
Lines 1-332 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.io.FileNotFoundException;
23
import java.io.PrintWriter;
24
import java.util.Properties;
25
import java.util.Vector;
26
27
import org.apache.lenya.xml.xpointer.XPointer;
28
import org.apache.log4j.Category;
29
import org.w3c.dom.Document;
30
import org.w3c.dom.Element;
31
import org.w3c.dom.Node;
32
import org.w3c.dom.NodeList;
33
34
public class XPointerFactory {
35
    static Category log = Category.getInstance(XPointerFactory.class);
36
    XPointer xpointer = null;
37
38
    /**
39
     * Creates a new XPointerFactory object.
40
     */
41
    public XPointerFactory() {
42
        Properties properties = new Properties();
43
        String propertiesFileName = "conf.properties";
44
45
        try {
46
            properties.load(XPointerFactory.class.getResourceAsStream(propertiesFileName));
47
        } catch (Exception e) {
48
            log.fatal(": Failed to load properties from resource: " + propertiesFileName);
49
        }
50
51
        String xpointerName = properties.getProperty("XPointer");
52
53
        if (xpointerName == null) {
54
            log.fatal(": No XPointer specified in " + propertiesFileName);
55
        }
56
57
        try {
58
            Class xpointerClass = Class.forName(xpointerName);
59
            xpointer = (XPointer) xpointerClass.newInstance();
60
        } catch (Exception e) {
61
            log.fatal(": " + e);
62
        }
63
    }
64
65
    /**
66
     * DOCUMENT ME!
67
     *
68
     * @param args DOCUMENT ME!
69
     */
70
    public static void main(String[] args) {
71
        XPointerFactory xpf = new XPointerFactory();
72
        DOMParserFactory dpf = new DOMParserFactory();
73
74
        if (args.length != 2) {
75
            System.err.println("Usage: java " + xpf.getClass().getName() +
76
                " example.xml \"/Example/People/Person[1]/Name\"");
77
78
            return;
79
        }
80
81
        Document document = null;
82
83
        try {
84
            document = dpf.getDocument(args[0]);
85
        } catch (FileNotFoundException e) {
86
            System.err.println("No such file or directory: " + e.getMessage());
87
        } catch (Exception e) {
88
            System.err.println(e.getMessage());
89
        }
90
91
        String xpath = args[1];
92
93
        try {
94
            Vector nodes = xpf.select(document.getDocumentElement(), "xpointer(" + xpath + ")");
95
            String[] values = xpf.getNodeValues(nodes);
96
97
            for (int i = 0; i < nodes.size(); i++) {
98
                System.out.println(((Node) nodes.elementAt(i)).getNodeName() + ": " + values[i]);
99
            }
100
        } catch (Exception e) {
101
            System.err.println(xpf.getClass().getName() + ".main(): " + e);
102
        }
103
104
        Document doc = xpf.employees();
105
106
        try {
107
            Vector nodes = xpf.select(doc.getDocumentElement(), "xpointer(/Employees/Employee[2])");
108
            String[] values = xpf.getNodeValues(nodes);
109
110
            for (int i = 0; i < nodes.size(); i++) {
111
                System.out.println(((Node) nodes.elementAt(i)).getNodeName() + ": " + values[i]);
112
            }
113
114
            Element leviElement = (Element) nodes.elementAt(0);
115
            leviElement.appendChild(dpf.newTextNode(doc, " Brucker"));
116
        } catch (Exception e) {
117
            System.err.println(xpf.getClass().getName() + ".main(): " + e);
118
        }
119
120
        new DOMWriter(new PrintWriter(System.out)).print(doc);
121
        System.out.println("");
122
    }
123
124
    /**
125
     * Parse reference for xpointer and namespaces
126
     *
127
     * @param reference xmlns(...)xpointer(...)xpointer(...)
128
     *
129
     * @exception MalformedXPointerException xpointer(xpath)
130
     */
131
    public void parse(String reference, Vector xpaths, Vector namespaces) throws MalformedXPointerException {
132
        tokenize(reference, xpaths, namespaces);
133
    }
134
135
    /**
136
     * Select nodes by xpointer
137
     *
138
     * @param node Document Node
139
     * @param reference xmls(...)xpointer(...)
140
     *
141
     * @return nodes
142
     *
143
     * @exception Exception ...
144
     */
145
    public Vector select(Node node, String reference) throws Exception {
146
        Vector xpaths = new Vector();
147
        Vector namespaces = new Vector();
148
        parse(reference, xpaths, namespaces);
149
150
        Vector nodes = new Vector();
151
152
        for (int i = 0; i < xpaths.size(); i++) {
153
            Vector n = xpointer.select(node, (String) xpaths.elementAt(i), namespaces);
154
155
            for (int j = 0; j < n.size(); j++) {
156
                nodes.addElement(n.elementAt(j));
157
            }
158
        }
159
160
        return nodes;
161
    }
162
163
    /**
164
     * Select nodes by xpointer and return node at specific position
165
     *
166
     * @param node Document Node
167
     * @param reference xmls(...)xpointer(...)
168
     *
169
     * @return node
170
     *
171
     * @exception Exception ...
172
     */
173
    public Node selectAt(Node node, String reference, int i) throws Exception {
174
        return (Node)select(node, reference).elementAt(i);
175
    }
176
177
    /**
178
     * DOCUMENT ME!
179
     *
180
     * @param xpointer DOCUMENT ME!
181
     * @param xpaths DOCUMENT ME!
182
     *
183
     * @exception MalformedXPointerException xpointer(xpath)xpointer(xpath)
184
     */
185
    public void tokenize(String xpointer, Vector xpaths, Vector namespaces) throws MalformedXPointerException {
186
        if ((xpointer.indexOf("xpointer(") == 0) && (xpointer.charAt(xpointer.length() - 1) == ')')) {
187
188
            String substring = xpointer.substring(9, xpointer.length());
189
            int i = substring.indexOf(")");
190
191
            if (i >= 0) {
192
                log.debug("XPath: " + substring.substring(0, i));
193
                xpaths.addElement(substring.substring(0, i));
194
                tokenize(substring.substring(i + 1, substring.length()), xpaths, namespaces);
195
            } else {
196
                xpaths.addElement(substring.substring(0, substring.length() - 1));
197
                return;
198
            }
199
	} else if ((xpointer.indexOf("xmlns(") == 0) && (xpointer.charAt(xpointer.length() - 1) == ')')) {
200
            String substring = xpointer.substring(6, xpointer.length());
201
            int i = substring.indexOf(")");
202
203
            if (i >= 0) {
204
                log.debug("Namespace: " + substring.substring(0, i));
205
                namespaces.addElement(substring.substring(0, i));
206
                tokenize(substring.substring(i + 1, substring.length()), xpaths, namespaces);
207
            } else {
208
                xpaths.addElement(substring.substring(0, substring.length() - 1));
209
                return;
210
            }
211
	} else if (xpointer.equals("")) {
212
                return;
213
        } else {
214
            throw new MalformedXPointerException(xpointer);
215
        }
216
    }
217
218
    /**
219
     * DOCUMENT ME!
220
     *
221
     * @param nodes DOCUMENT ME!
222
     *
223
     * @return DOCUMENT ME!
224
     *
225
     * @throws Exception DOCUMENT ME!
226
     */
227
    public String[] getNodeValues(Vector nodes) throws Exception {
228
        String[] values = new String[nodes.size()];
229
230
        for (int i = 0; i < values.length; i++) {
231
            Node node = (Node) nodes.elementAt(i);
232
            short type = node.getNodeType();
233
234
            switch (type) {
235
            case Node.ELEMENT_NODE: {
236
                values[i] = getElementValue((Element) node);
237
238
                break;
239
            }
240
241
            case Node.ATTRIBUTE_NODE: {
242
                values[i] = node.getNodeValue();
243
244
                break;
245
            }
246
247
            default:
248
                values[i] = "";
249
                throw new Exception("Neither ELEMENT nor ATTRIBUTE: " + type);
250
            }
251
        }
252
253
        return values;
254
    }
255
256
    /**
257
     * DOCUMENT ME!
258
     *
259
     * @param element DOCUMENT ME!
260
     *
261
     * @return DOCUMENT ME!
262
     */
263
    public String getElementValue(Element element) {
264
        String value = "";
265
        NodeList nl = element.getChildNodes();
266
267
        for (int k = 0; k < nl.getLength(); k++) {
268
            short nodeType = nl.item(k).getNodeType();
269
270
            if (nodeType == Node.TEXT_NODE) {
271
                value = value + nl.item(k).getNodeValue();
272
            } else if (nodeType == Node.ELEMENT_NODE) {
273
                value = value + getElementValue((Element) nl.item(k));
274
            } else {
275
                System.err.println("EXCEPTION: " + this.getClass().getName() +
276
                    ".getElementValue(): No TEXT_NODE");
277
            }
278
        }
279
280
        return value;
281
    }
282
283
    /**
284
     * DOCUMENT ME!
285
     *
286
     * @param element DOCUMENT ME!
287
     * @param text DOCUMENT ME!
288
     */
289
    public void getElementValue(Element element, Vector text) {
290
        NodeList nl = element.getChildNodes();
291
292
        for (int k = 0; k < nl.getLength(); k++) {
293
            short nodeType = nl.item(k).getNodeType();
294
295
            if (nodeType == Node.TEXT_NODE) {
296
                text.addElement(nl.item(k).getNodeValue());
297
            } else if (nodeType == Node.ELEMENT_NODE) {
298
                getElementValue((Element) nl.item(k), text);
299
            } else {
300
                System.err.println("EXCEPTION: " + this.getClass().getName() +
301
                    ".getElementValue(): No TEXT_NODE");
302
            }
303
        }
304
    }
305
306
    /**
307
     * DOCUMENT ME!
308
     *
309
     * @return DOCUMENT ME!
310
     */
311
    public Document employees() {
312
        DOMParserFactory dpf = new DOMParserFactory();
313
        Document doc = dpf.getDocument();
314
        Element michi = dpf.newElementNode(doc, "Employee");
315
        michi.setAttribute("Id", "0");
316
        michi.appendChild(dpf.newTextNode(doc, "Michi"));
317
318
        Element levi = dpf.newElementNode(doc, "Employee");
319
        levi.setAttribute("Id", "1");
320
        levi.appendChild(dpf.newTextNode(doc, "Levi"));
321
322
        Element employees = dpf.newElementNode(doc, "Employees");
323
        employees.appendChild(dpf.newTextNode(doc, "\n"));
324
        employees.appendChild(michi);
325
        employees.appendChild(dpf.newTextNode(doc, "\n"));
326
        employees.appendChild(levi);
327
        employees.appendChild(dpf.newTextNode(doc, "\n"));
328
        doc.appendChild(employees);
329
330
        return doc;
331
    }
332
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/Normalize.java (-266 lines)
Lines 1-266 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
23
/**
24
 * @deprecated 
25
 */
26
public class Normalize {
27
    /**
28
     * DOCUMENT ME!
29
     *
30
     * @param args DOCUMENT ME!
31
     */
32
    public static void main(String[] args) {
33
        System.out.println(Normalize.normalize("&"));
34
        System.out.println(Normalize.denormalize("Z&#252;rich"));
35
        System.out.println(Normalize.denormalize("Z&252;rich &#38; Region&#787dj&#356;"));
36
    }
37
38
    /**
39
     *
40
     */
41
    public static String normalize(String s) {
42
        StringBuffer sb = new StringBuffer();
43
44
        for (int i = 0; i < s.length(); i++) {
45
            char ch = s.charAt(i);
46
47
            switch (ch) {
48
            case '&': // 38
49
             {
50
                sb.append("&#38;");
51
52
                break;
53
            }
54
55
            case 60: // <
56
             {
57
                sb.append("&#60;");
58
59
                break;
60
            }
61
62
            case 62: // >
63
             {
64
                sb.append("&#62;");
65
66
                break;
67
            }
68
69
            case 139: // <
70
             {
71
                sb.append("&#139;");
72
73
                break;
74
            }
75
76
            case 155: // >
77
             {
78
                sb.append("&#155;");
79
80
                break;
81
            }
82
83
            case 160: // nbsp
84
             {
85
                sb.append("&#160;");
86
87
                break;
88
            }
89
90
            case 171: // <<
91
             {
92
                sb.append("&#171;");
93
94
                break;
95
            }
96
97
            case 183: // .
98
             {
99
                sb.append("&#183;");
100
101
                break;
102
            }
103
104
            case 187: // >>
105
             {
106
                sb.append("&#187;");
107
108
                break;
109
            }
110
111
            case 196: // Ae
112
             {
113
                sb.append("&#196;");
114
115
                break;
116
            }
117
118
            case 214: // Oe
119
             {
120
                sb.append("&#214;");
121
122
                break;
123
            }
124
125
            case 220: // Ue
126
             {
127
                sb.append("&#220;");
128
129
                break;
130
            }
131
132
            case 223: // Scharfes S
133
             {
134
                sb.append("&#223;");
135
136
                break;
137
            }
138
139
            case 225: // aacute
140
             {
141
                sb.append("&#225;");
142
143
                break;
144
            }
145
146
            case 228: // ae
147
             {
148
                sb.append("&#228;");
149
150
                break;
151
            }
152
153
            case 232: // egrave
154
             {
155
                sb.append("&#232;");
156
157
                break;
158
            }
159
160
            case 233: // eacute
161
             {
162
                sb.append("&#233;");
163
164
                break;
165
            }
166
167
            case 234: // ecirc
168
             {
169
                sb.append("&#234;");
170
171
                break;
172
            }
173
174
            case 244: // ocirc
175
             {
176
                sb.append("&#244;");
177
178
                break;
179
            }
180
181
            case 246: // oe
182
             {
183
                sb.append("&#246;");
184
185
                break;
186
            }
187
188
            case 252: // ue
189
             {
190
                sb.append("&#252;");
191
192
                break;
193
            }
194
195
            default:sb.append(ch);
196
            }
197
        }
198
199
        return sb.toString();
200
    }
201
202
    /**
203
     *
204
     */
205
    public static String denormalize(String s) {
206
        StringBuffer sb = new StringBuffer();
207
208
        for (int i = 0; i < s.length(); i++) {
209
            char ch = s.charAt(i);
210
211
            if (ch == '&') {
212
                StringBuffer substring = new StringBuffer();
213
                int length = i + 6;
214
215
                if (length > s.length()) {
216
                    length = s.length();
217
                }
218
219
                for (int k = i; k < length; k++) {
220
                    substring.append(s.charAt(k));
221
222
                    if (s.charAt(k) == ';') {
223
                        break;
224
                    }
225
                }
226
227
                if (substring.length() > 3) {
228
                    if ((substring.charAt(1) != '#') ||
229
                            (substring.charAt(substring.length() - 1) != ';')) {
230
                        sb.append(ch);
231
                    } else {
232
                        int ascii = 0;
233
                        int power = 1;
234
235
                        for (int j = substring.length() - 2; j >= 2; j--) {
236
                            try {
237
                                Integer integer = new Integer("" + substring.charAt(j));
238
                                ascii = ascii + (power * integer.intValue());
239
                            } catch (Exception e) {
240
                                ascii = -1;
241
242
                                break;
243
                            }
244
245
                            power = power * 10;
246
                        }
247
248
                        if (ascii >= 0) {
249
                            char character = (char) ascii;
250
                            sb.append(character);
251
                            i = (i + substring.length()) - 1;
252
                        } else {
253
                            sb.append(ch);
254
                        }
255
                    }
256
                } else {
257
                    sb.append(ch);
258
                }
259
            } else {
260
                sb.append(ch);
261
            }
262
        }
263
264
        return sb.toString();
265
    }
266
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/conf.properties (-20 lines)
Lines 1-20 Link Here
1
# Copyright 1999-2004 The Apache Software Foundation
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
15
# DOM Parser
16
Parser=org.apache.lenya.xml.parser.XercesParser
17
# SAX Parser
18
SAXParser=org.apache.xerces.parsers.SAXParser
19
# XPointer, XPath
20
XPointer=org.apache.lenya.xml.xpointer.XalanXPointer
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XPSSourceInformation.java (-218 lines)
Lines 1-218 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.io.File;
23
import java.io.IOException;
24
import java.net.MalformedURLException;
25
import java.net.URL;
26
import java.util.Vector;
27
28
import org.apache.log4j.Category;
29
30
public class XPSSourceInformation {
31
    static Category log = Category.getInstance(XPSSourceInformation.class);
32
    public int lineNumber = -1;
33
    public URL url = null;
34
    public XPSSourceInformation parentInfo = null;
35
    public Vector children = null;
36
    String offset = null;
37
    String cocoon = null;
38
39
    /**
40
     * Creates a new XPSSourceInformation object.
41
     *
42
     * @param fileURL DOCUMENT ME!
43
     * @param cocoon DOCUMENT ME!
44
     */
45
    public XPSSourceInformation(String fileURL, String cocoon) {
46
        this.cocoon = cocoon;
47
48
        parentInfo = null;
49
        offset = "++";
50
        children = new Vector();
51
52
        try {
53
            url = new URL(fileURL);
54
        } catch (MalformedURLException e) {
55
            log.error(e);
56
        }
57
    }
58
59
    /**
60
     * Creates a new XPSSourceInformation object.
61
     *
62
     * @param urlString DOCUMENT ME!
63
     * @param parentInfo DOCUMENT ME!
64
     * @param cocoon DOCUMENT ME!
65
     */
66
    public XPSSourceInformation(String urlString, XPSSourceInformation parentInfo, String cocoon) {
67
        this.cocoon = cocoon;
68
69
        this.parentInfo = parentInfo;
70
        offset = "++";
71
        children = new Vector();
72
73
        try {
74
            if (urlString.indexOf("/") == 0) {
75
                url = new URL("file:" + urlString);
76
            } else if (urlString.indexOf("cocoon:") == 0) {
77
                if (cocoon != null) {
78
                    url = new URL(cocoon + "/" + urlString.substring(7)); // remove "cocoon:" protocol
79
                    log.warn("Protocol 7789: COCOON (" + urlString +
80
                        ") -- will be transformed into http: " + url);
81
                } else {
82
                    log.error("No cocoon base set!");
83
                }
84
            } else {
85
                url = new URL(urlString);
86
            }
87
88
            String p = url.getProtocol();
89
90
            // Does not make sense, because it will be either file or http, and else an Exception will be thrown!
91
            if (!(p.equals("http") || p.equals("file") || p.equals("class"))) {
92
                log.error("This type of protocol is not supported yet: " + p);
93
            }
94
        } catch (MalformedURLException e) // let's hope it's a relative path
95
         {
96
            log.debug("1079: " + e + " -- Let's hope it's a relative path!");
97
98
            File parent = new File(parentInfo.url.getFile());
99
100
            // transform URI to system-independent path and create absolute path
101
            try {
102
                int index = urlString.indexOf("#");
103
                String xpointer = "";
104
                String relativePath = urlString;
105
106
                if (index != -1) {
107
                    relativePath = urlString.substring(0, index);
108
                    xpointer = urlString.substring(index);
109
                }
110
111
                relativePath = relativePath.replace('/', File.separatorChar);
112
113
                File file = new File(parent.getParentFile(), relativePath);
114
115
                url = new URL("file", null, -1, file.getCanonicalPath() + xpointer);
116
117
                log.info("Concatenated URL: " + url);
118
            } catch (MalformedURLException exception) {
119
                log.error(exception);
120
            } catch (IOException exception) {
121
                log.error(exception);
122
            }
123
        }
124
125
        if (url.getProtocol().equals("http")) {
126
        } else if (url.getProtocol().equals("file")) {
127
            if (parentInfo.url.getProtocol().equals("http")) {
128
                String protocol = parentInfo.url.getProtocol();
129
                String host = parentInfo.url.getHost();
130
                int port = parentInfo.url.getPort();
131
132
                try {
133
                    if (url.getRef() != null) {
134
                        url = new URL(protocol, host, port, url.getFile() + "#" + url.getRef());
135
                    } else {
136
                        url = new URL(protocol, host, port, url.getFile());
137
                    }
138
                } catch (MalformedURLException e) {
139
                    log.error(e);
140
                }
141
            }
142
        } else {
143
            log.error("EXCEPTION: 0.2.21");
144
        }
145
    }
146
147
    /**
148
     * DOCUMENT ME!
149
     *
150
     * @param args DOCUMENT ME!
151
     */
152
    public static void main(String[] args) {
153
        String cocoon = null;
154
        XPSSourceInformation xpssf = new XPSSourceInformation(args[0], cocoon);
155
        System.out.println(xpssf);
156
    }
157
158
    /**
159
     * DOCUMENT ME!
160
     *
161
     * @param child DOCUMENT ME!
162
     */
163
    public void addChild(XPSSourceInformation child) {
164
        children.addElement(child);
165
    }
166
167
    /**
168
     * DOCUMENT ME!
169
     *
170
     * @return DOCUMENT ME!
171
     */
172
    public String toString() {
173
        return toString("", offset);
174
    }
175
176
    /**
177
     * DOCUMENT ME!
178
     *
179
     * @param index DOCUMENT ME!
180
     * @param offset DOCUMENT ME!
181
     *
182
     * @return DOCUMENT ME!
183
     */
184
    public String toString(String index, String offset) {
185
        String s = index + url.toString() + "\n";
186
187
        for (int i = 0; i < children.size(); i++) {
188
            XPSSourceInformation child = (XPSSourceInformation) children.elementAt(i);
189
            s = s + child.toString(index + offset, offset);
190
        }
191
192
        return s;
193
    }
194
195
    /**
196
     * Check for XInclude Loops
197
     *
198
     * @param xpssf DOCUMENT ME!
199
     * @param url DOCUMENT ME!
200
     *
201
     * @return DOCUMENT ME!
202
     */
203
    public boolean checkLoop(XPSSourceInformation xpssf, URL url) {
204
        if (xpssf.url.getFile().equals(url.getFile())) {
205
            if (xpssf.parentInfo != null) {
206
                return true;
207
            } else {
208
                return false; // This is just the request (it can be dummy.xml but also something real)
209
            }
210
        }
211
212
        if (xpssf.parentInfo != null) {
213
            return checkLoop(xpssf.parentInfo, url);
214
        }
215
216
        return false;
217
    }
218
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/Configuration.java (-155 lines)
Lines 1-155 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.net.URL;
23
import java.util.Properties;
24
25
import org.apache.log4j.Category;
26
27
28
/**
29
 * Reads xpsconf.properties
30
 * @deprecated replaced by config/ directory
31
 */
32
public class Configuration {
33
    static Category log = Category.getInstance(Configuration.class);
34
    public static final String DEFAULT_CONFIGURATION_FILE = "org/apache/lenya/xml/xpsconf.properties";
35
    public static final String DEFAULT_CONFIGURATION_KEY = "xps.configuration";
36
    public static final String OVERRIDE_DEFAULT_CONFIGURATION_KEY = "override.xps.configuration";
37
    public String cacheFolder = null;
38
    public boolean cacheHTTP = false;
39
    public String INCLUDE = null;
40
    public String JAVA_ZONE = null;
41
    public String proxyHost = null;
42
    public String proxyPort = null;
43
44
    /**
45
     * Creates a new Configuration object.
46
     */
47
    public Configuration() {
48
        getProperties(load());
49
    }
50
51
    /**
52
     * http://www.artima.com/java/answers/Mar2001/messages/164.html export
53
     * CLASSPATH=/home/lenya/src/xps/build/properties:... java
54
     * -Doverride.xps.configuration=org/apache/lenya/xps/altconf.properties org.apache.lenya.xps.Configuration
55
     *
56
     * @param args DOCUMENT ME!
57
     */
58
    public static void main(String[] args) {
59
        Configuration conf = new Configuration();
60
61
        System.out.println("Caching directory: " + conf.cacheFolder);
62
        System.out.println("Cache xml from http connections: " + conf.cacheHTTP);
63
64
        if ((conf.proxyHost != null) && (conf.proxyHost != null)) {
65
            System.out.println("Proxy set:");
66
            System.out.println(conf.proxyHost);
67
            System.out.println(conf.proxyPort);
68
        } else {
69
            System.out.println("No proxy set.");
70
        }
71
    }
72
73
    /**
74
     * DOCUMENT ME!
75
     *
76
     * @return DOCUMENT ME!
77
     */
78
    public static Properties load() {
79
        String resourcePathRelativeToClasspath = System.getProperty(OVERRIDE_DEFAULT_CONFIGURATION_KEY);
80
81
        if (resourcePathRelativeToClasspath == null) {
82
            resourcePathRelativeToClasspath = System.getProperty(DEFAULT_CONFIGURATION_KEY,
83
                    DEFAULT_CONFIGURATION_FILE);
84
            log.debug(DEFAULT_CONFIGURATION_KEY + "=" + resourcePathRelativeToClasspath);
85
        } else {
86
            log.debug(OVERRIDE_DEFAULT_CONFIGURATION_KEY + "=" + resourcePathRelativeToClasspath);
87
        }
88
89
        ClassLoader cl = ClassLoader.getSystemClassLoader();
90
91
        // FIXME:
92
        URL url = org.apache.log4j.helpers.Loader.getResource("hallo");
93
94
        if (url == null) {
95
            //return null;
96
        }
97
98
        log.debug(url);
99
100
        Properties properties = new Properties();
101
102
        try {
103
            properties.load(Configuration.class.getResourceAsStream("xpsconf.properties"));
104
        } catch (Exception e) {
105
            log.error(".load(): " + e);
106
        }
107
108
        return properties;
109
    }
110
111
    /**
112
     * DOCUMENT ME!
113
     *
114
     * @param properties DOCUMENT ME!
115
     */
116
    public void getProperties(Properties properties) {
117
        if (properties != null) {
118
            cacheFolder = getProperty(properties,
119
                    "org.apache.lenya.xps.XLinkInterpreter.cacheFolder");
120
            cacheHTTP = false;
121
            INCLUDE = getProperty(properties, "Include");
122
            JAVA_ZONE = getProperty(properties, "JavaZone");
123
            proxyHost = null;
124
            proxyPort = null;
125
        }
126
    }
127
128
    /**
129
     * DOCUMENT ME!
130
     *
131
     * @param properties DOCUMENT ME!
132
     * @param key DOCUMENT ME!
133
     *
134
     * @return DOCUMENT ME!
135
     */
136
    public String getProperty(Properties properties, String key) {
137
        String value = properties.getProperty(key);
138
139
        if (value != null) {
140
            log.debug(key + "=" + value);
141
142
            return value;
143
        } else {
144
            log.debug(".getProperty(): No such property: " + key);
145
        }
146
147
        return null;
148
    }
149
150
    /**
151
     * DOCUMENT ME!
152
     */
153
    public static void register() {
154
    }
155
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XInclude.java (-35 lines)
Lines 1-35 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.util.Vector;
23
24
public interface XInclude {
25
    /**
26
     * The Lenya XInclude implementation. It improves on the Cocoon implementation by supporting nested includes and
27
     * better error handling.
28
     *
29
     * @param args DOCUMENT ME!
30
     * @param parentInfo DOCUMENT ME!
31
     *
32
     * @return DOCUMENT ME!
33
     */
34
    public Vector include(String[] args, XPSSourceInformation parentInfo);
35
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/parser/XercesParser.java (-204 lines)
Lines 1-204 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml.parser;
21
22
import java.io.InputStream;
23
import java.io.PrintWriter;
24
import java.io.Reader;
25
26
import org.apache.lenya.xml.DOMWriter;
27
import org.apache.xerces.dom.CDATASectionImpl;
28
import org.apache.xerces.dom.CommentImpl;
29
import org.apache.xerces.dom.DocumentImpl;
30
import org.apache.xerces.dom.ElementImpl;
31
import org.apache.xerces.dom.TextImpl;
32
import org.apache.xerces.parsers.DOMParser;
33
import org.w3c.dom.CDATASection;
34
import org.w3c.dom.Comment;
35
import org.w3c.dom.Document;
36
import org.w3c.dom.Element;
37
import org.w3c.dom.Text;
38
39
40
/**
41
 * Xerces Parser Implementation
42
 */
43
public class XercesParser implements Parser {
44
    /**
45
     * DOCUMENT ME!
46
     *
47
     * @param args DOCUMENT ME!
48
     */
49
    public static void main(String[] args) {
50
        Parser parser = new XercesParser();
51
52
        if (args.length != 1) {
53
            System.err.println("Usage: java " + parser.getClass().getName() + " example.xml");
54
55
            return;
56
        }
57
58
        Document doc = null;
59
60
        try {
61
            doc = parser.getDocument(args[0]);
62
        } catch (Exception e) {
63
            System.err.println(e);
64
        }
65
66
        new DOMWriter(new PrintWriter(System.out)).print(doc);
67
        System.out.println("");
68
69
        Document document = parser.getDocument();
70
        Element michi = parser.newElementNode(document, "Employee");
71
        michi.setAttribute("Id", "michi");
72
        michi.appendChild(parser.newTextNode(document, "Michi"));
73
74
        Element employees = parser.newElementNode(document, "Employees");
75
        employees.appendChild(parser.newTextNode(document, "\n"));
76
        employees.appendChild(michi);
77
        employees.appendChild(parser.newTextNode(document, "\n"));
78
        document.appendChild(employees);
79
        new DOMWriter(new PrintWriter(System.out)).print(document);
80
        System.out.println("");
81
    }
82
83
    /**
84
     * DOCUMENT ME!
85
     *
86
     * @param filename DOCUMENT ME!
87
     *
88
     * @return DOCUMENT ME!
89
     *
90
     * @throws Exception DOCUMENT ME!
91
     */
92
    public Document getDocument(String filename) throws Exception {
93
        DOMParser parser = new DOMParser();
94
95
        org.xml.sax.InputSource in = new org.xml.sax.InputSource(filename);
96
        parser.parse(in);
97
98
        return parser.getDocument();
99
    }
100
101
    /**
102
     * DOCUMENT ME!
103
     *
104
     * @param is DOCUMENT ME!
105
     *
106
     * @return DOCUMENT ME!
107
     *
108
     * @throws Exception DOCUMENT ME!
109
     */
110
    public Document getDocument(InputStream is) throws Exception {
111
        DOMParser parser = new DOMParser();
112
        org.xml.sax.InputSource in = new org.xml.sax.InputSource(is);
113
        parser.parse(in);
114
115
        return parser.getDocument();
116
    }
117
118
    /**
119
     * Creates a document from a reader.
120
     *
121
     * @param is DOCUMENT ME!
122
     *
123
     * @return DOCUMENT ME!
124
     *
125
     * @throws Exception DOCUMENT ME!
126
     */
127
    public Document getDocument(Reader reader) throws Exception {
128
        DOMParser parser = new DOMParser();
129
        org.xml.sax.InputSource in = new org.xml.sax.InputSource(reader);
130
        parser.parse(in);
131
132
        return parser.getDocument();
133
    }
134
135
    /**
136
     * DOCUMENT ME!
137
     *
138
     * @return DOCUMENT ME!
139
     */
140
    public Document getDocument() {
141
        return new DocumentImpl();
142
    }
143
144
    /**
145
     * DOCUMENT ME!
146
     *
147
     * @param document DOCUMENT ME!
148
     * @param name DOCUMENT ME!
149
     *
150
     * @return DOCUMENT ME!
151
     */
152
    public Element newElementNode(Document document, String name) {
153
        return new ElementImpl((DocumentImpl) document, name);
154
    }
155
156
    /**
157
     * Creates an element with namespace support.
158
     *
159
     * @param document The owner document.
160
     * @param namespaceUri The namespace URI of the element.
161
     * @param qualifiedName The qualified name of the element.
162
     *
163
     * @return An element.
164
     */
165
    public Element newElementNSNode(Document document, String namespaceUri, String qualifiedName) {
166
        return document.createElementNS(namespaceUri, qualifiedName);
167
    }
168
169
    /**
170
     * DOCUMENT ME!
171
     *
172
     * @param document DOCUMENT ME!
173
     * @param data DOCUMENT ME!
174
     *
175
     * @return DOCUMENT ME!
176
     */
177
    public Text newTextNode(Document document, String data) {
178
        return new TextImpl((DocumentImpl) document, data);
179
    }
180
181
    /**
182
     * CDATA
183
     *
184
     * @param document DOM Document
185
     * @param data Text
186
     *
187
     * @return CDATASection
188
     */
189
    public CDATASection newCDATASection(Document document, String data) {
190
        return new CDATASectionImpl((DocumentImpl) document, data);
191
    }
192
193
    /**
194
     * DOCUMENT ME!
195
     *
196
     * @param document DOCUMENT ME!
197
     * @param data DOCUMENT ME!
198
     *
199
     * @return DOCUMENT ME!
200
     */
201
    public Comment newCommentNode(Document document, String data) {
202
        return new CommentImpl((DocumentImpl) document, data);
203
    }
204
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/parser/Parser.java (-127 lines)
Lines 1-127 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml.parser;
21
22
import java.io.InputStream;
23
import java.io.Reader;
24
25
import org.w3c.dom.CDATASection;
26
import org.w3c.dom.Comment;
27
import org.w3c.dom.Document;
28
import org.w3c.dom.Element;
29
import org.w3c.dom.Text;
30
31
32
/**
33
 * DOM Parser interface
34
 */
35
public interface Parser {
36
    /**
37
     * DOCUMENT ME!
38
     *
39
     * @param filename DOCUMENT ME!
40
     *
41
     * @return DOCUMENT ME!
42
     *
43
     * @throws Exception DOCUMENT ME!
44
     */
45
    Document getDocument(String filename) throws Exception;
46
47
    /**
48
     * DOCUMENT ME!
49
     *
50
     * Create a document from a reader.
51
     * @param is DOCUMENT ME!
52
     *
53
     * @return DOCUMENT ME!
54
     *
55
     * @throws Exception DOCUMENT ME!
56
     */
57
    Document getDocument(Reader reader) throws Exception;
58
59
    /**
60
     * DOCUMENT ME!
61
     *
62
     * @param is DOCUMENT ME!
63
     *
64
     * @return DOCUMENT ME!
65
     *
66
     * @throws Exception DOCUMENT ME!
67
     */
68
    Document getDocument(InputStream is) throws Exception;
69
70
    /**
71
     * DOCUMENT ME!
72
     *
73
     * @return DOCUMENT ME!
74
     */
75
    Document getDocument();
76
77
    /**
78
     * DOCUMENT ME!
79
     *
80
     * @param document DOCUMENT ME!
81
     * @param name DOCUMENT ME!
82
     *
83
     * @return DOCUMENT ME!
84
     */
85
    Element newElementNode(Document document, String name);
86
87
    /**
88
     * Creates an element with namespace support.
89
     *
90
     * @param document The owner document.
91
     * @param namespaceUri The namespace URI of the element.
92
     * @param qualifiedName The qualified name of the element.
93
     *
94
     * @return An element.
95
     */
96
    Element newElementNSNode(Document document, String namespaceUri, String qualifiedName);
97
        
98
    /**
99
     * DOCUMENT ME!
100
     *
101
     * @param document DOCUMENT ME!
102
     * @param data DOCUMENT ME!
103
     *
104
     * @return DOCUMENT ME!
105
     */
106
    Text newTextNode(Document document, String data);
107
108
    /**
109
     * CDATA
110
     *
111
     * @param document DOM Document
112
     * @param data Text
113
     *
114
     * @return CDATASection
115
     */
116
    CDATASection newCDATASection(Document document, String data);
117
118
    /**
119
     * DOCUMENT ME!
120
     *
121
     * @param document DOCUMENT ME!
122
     * @param data DOCUMENT ME!
123
     *
124
     * @return DOCUMENT ME!
125
     */
126
    Comment newCommentNode(Document document, String data);
127
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/DOMWriter.java (-359 lines)
Lines 1-359 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.io.BufferedWriter;
23
import java.io.FileNotFoundException;
24
import java.io.OutputStream;
25
import java.io.OutputStreamWriter;
26
import java.io.PrintWriter;
27
import java.util.Vector;
28
29
import org.apache.log4j.Category;
30
import org.w3c.dom.Document;
31
import org.w3c.dom.Element;
32
import org.w3c.dom.NamedNodeMap;
33
import org.w3c.dom.Node;
34
import org.w3c.dom.NodeList;
35
36
37
/**
38
 * DOCUMENT ME!
39
 * @deprecated replaced by DocumentHelper
40
 */
41
public class DOMWriter {
42
    static Category log = Category.getInstance(DOMWriter.class);
43
    PrintWriter out = null;
44
    String encoding = null;
45
46
    /**
47
     * Creates a new DOMWriter object.
48
     *
49
     * @param out DOCUMENT ME!
50
     */
51
    public DOMWriter(PrintWriter out) {
52
        this.out = out;
53
    }
54
55
    /**
56
     * Creates a new DOMWriter object.
57
     *
58
     * @param out DOCUMENT ME!
59
     * @param encoding DOCUMENT ME!
60
     */
61
    public DOMWriter(PrintWriter out, String encoding) {
62
        this(out);
63
        this.encoding = encoding;
64
    }
65
66
    /**
67
     * Creates a new DOMWriter object.
68
     *
69
     * @param os DOCUMENT ME!
70
     *
71
     * @throws Exception DOCUMENT ME!
72
     */
73
    public DOMWriter(OutputStream os) throws Exception {
74
        this(os, "utf-8");
75
    }
76
77
    /**
78
     * Creates a new DOMWriter object.
79
     *
80
     * @param os DOCUMENT ME!
81
     * @param encoding DOCUMENT ME!
82
     *
83
     * @throws Exception DOCUMENT ME!
84
     */
85
    public DOMWriter(OutputStream os, String encoding)
86
        throws Exception {
87
        out = new PrintWriter(new BufferedWriter(
88
                    new OutputStreamWriter(os, XMLEncToJavaEnc.getJava(encoding))));
89
        this.encoding = encoding;
90
    }
91
92
    /**
93
     * DOCUMENT ME!
94
     *
95
     * @param args DOCUMENT ME!
96
     */
97
    public static void main(String[] args) {
98
        if (args.length != 1) {
99
            System.err.println("Usage: java org.apache.lenya.xml.DOMWriter \"file.xml\"");
100
            System.err.println("Description: Reads \"file.xml\" and writes it to standard output");
101
102
            return;
103
        }
104
105
        DOMParserFactory dpf = new DOMParserFactory();
106
        Document document = null;
107
108
        try {
109
            document = dpf.getDocument(args[0]);
110
        } catch (FileNotFoundException e) {
111
            System.err.println("No such file: " + e.getMessage());
112
113
            return;
114
        } catch (Exception e) {
115
            System.err.println(e.getMessage());
116
117
            return;
118
        }
119
120
        try {
121
            new DOMWriter(System.out, "iso-8859-1").printWithoutFormatting(document);
122
        } catch (Exception e) {
123
            System.err.println(e.getMessage());
124
125
            return;
126
        }
127
128
        log.fatal("\n");
129
130
        log.fatal(".main(): System.exit(0)");
131
        System.exit(0);
132
133
        new DOMWriter(new PrintWriter(System.out)).print(document);
134
        System.out.print("\n");
135
136
        XPointerFactory xpf = new XPointerFactory();
137
138
        try {
139
            Vector nodes = xpf.select(document.getDocumentElement(),
140
                    "xpointer(/Example/People/Person/City)");
141
            String[] values = xpf.getNodeValues(nodes);
142
143
            for (int i = 0; i < values.length; i++) {
144
                System.out.println(values[i]);
145
            }
146
147
            Document doc = dpf.getDocument();
148
            Element root = dpf.newElementNode(doc, "Root");
149
150
            //
151
            for (int i = 0; i < values.length; i++) {
152
                root.appendChild(dpf.newTextNode(doc, values[i]));
153
            }
154
155
            doc.appendChild(root);
156
            new DOMWriter(new PrintWriter(System.out)).print(doc);
157
            System.out.print("\n");
158
        } catch (Exception e) {
159
            System.err.println(e);
160
        }
161
    }
162
163
    /**
164
     * DOCUMENT ME!
165
     *
166
     * @param node DOCUMENT ME!
167
     */
168
    public void print(Node node) {
169
        if (node == null) {
170
            return;
171
        }
172
173
        short type = node.getNodeType();
174
175
        switch (type) {
176
        case Node.DOCUMENT_NODE: {
177
            out.print("<?xml version=\"1.0\"");
178
179
            if (encoding != null) {
180
                out.print(" encoding=\"" + encoding + "\"");
181
            }
182
183
            out.print("?>\n\n");
184
            print(((Document) node).getDocumentElement());
185
            out.flush();
186
187
            break;
188
        }
189
190
        case Node.ELEMENT_NODE: {
191
            out.print("<" + node.getNodeName());
192
193
            NamedNodeMap attributes = node.getAttributes();
194
195
            for (int i = 0; i < attributes.getLength(); i++) {
196
                Node attribute = attributes.item(i);
197
                out.print(" " + attribute.getNodeName() + "=\"" +
198
                    Normalize.normalize(attribute.getNodeValue()) + "\"");
199
            }
200
201
            if (node.hasChildNodes()) {
202
                out.print(">");
203
204
                NodeList children = node.getChildNodes();
205
206
                for (int i = 0; i < children.getLength(); i++) {
207
                    print(children.item(i));
208
                }
209
210
                out.print("</" + node.getNodeName() + ">");
211
            } else {
212
                out.print("/>");
213
            }
214
215
            break;
216
        }
217
218
        case Node.TEXT_NODE: {
219
            out.print(Normalize.normalize(node.getNodeValue()));
220
221
            break;
222
        }
223
224
        case Node.COMMENT_NODE: {
225
            out.print("<!--" + node.getNodeValue() + "-->");
226
227
            break;
228
        }
229
230
        default: {
231
            System.err.println(this.getClass().getName() + ".print(): Node type not implemented: " +
232
                type);
233
234
            break;
235
        }
236
        }
237
    }
238
239
    /**
240
     * DOCUMENT ME!
241
     *
242
     * @param node DOCUMENT ME!
243
     */
244
    public void printWithoutFormatting(Node node) {
245
        if (node == null) {
246
            return;
247
        }
248
249
        short type = node.getNodeType();
250
251
        switch (type) {
252
        case Node.DOCUMENT_NODE: {
253
            out.print("<?xml version=\"1.0\"");
254
255
            if (encoding != null) {
256
                out.print(" encoding=\"" + encoding + "\"");
257
            }
258
259
            out.print("?>\n\n");
260
261
            Element root = ((Document) node).getDocumentElement();
262
            root.setAttribute("xmlns:xlink", XLink.XLINK_NAMESPACE);
263
            printWithoutFormatting(root);
264
            out.flush();
265
266
            break;
267
        }
268
269
        case Node.ELEMENT_NODE: {
270
            out.print("<" + node.getNodeName());
271
272
            NamedNodeMap attributes = node.getAttributes();
273
274
            for (int i = 0; i < attributes.getLength(); i++) {
275
                Node attribute = attributes.item(i);
276
                out.print(" " + attribute.getNodeName() + "=\"" +
277
                    replaceSpecialCharacters(attribute.getNodeValue()) + "\"");
278
            }
279
280
            if (node.hasChildNodes()) {
281
                out.print(">");
282
283
                NodeList children = node.getChildNodes();
284
285
                for (int i = 0; i < children.getLength(); i++) {
286
                    printWithoutFormatting(children.item(i));
287
                }
288
289
                out.print("</" + node.getNodeName() + ">");
290
            } else {
291
                out.print("/>");
292
            }
293
294
            break;
295
        }
296
297
        case Node.TEXT_NODE: {
298
            out.print(replaceSpecialCharacters(node.getNodeValue()));
299
300
            break;
301
        }
302
303
        case Node.COMMENT_NODE: {
304
            out.print("<!--" + node.getNodeValue() + "-->");
305
306
            break;
307
        }
308
309
        default: {
310
            System.err.println(this.getClass().getName() + ".print(): Node type not implemented: " +
311
                type);
312
313
            break;
314
        }
315
        }
316
    }
317
318
    /**
319
     * DOCUMENT ME!
320
     *
321
     * @param s DOCUMENT ME!
322
     *
323
     * @return DOCUMENT ME!
324
     */
325
    public String replaceSpecialCharacters(String s) {
326
        StringBuffer str = new StringBuffer();
327
328
        int len = (s != null) ? s.length() : 0;
329
330
        for (int i = 0; i < len; i++) {
331
            char ch = s.charAt(i);
332
333
            switch (ch) {
334
            case '<': {
335
                str.append("&#60;");
336
337
                break;
338
            }
339
340
            case '>': {
341
                str.append("&#62;");
342
343
                break;
344
            }
345
346
            case '&': {
347
                str.append("&#38;");
348
349
                break;
350
            }
351
352
            default:
353
                str.append(ch);
354
            }
355
        }
356
357
        return (str.toString());
358
    }
359
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/DOMUtil.java (-515 lines)
Lines 1-515 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.io.StringReader;
23
import java.util.Vector;
24
25
import org.apache.log4j.Category;
26
import org.apache.xpath.XPathAPI;
27
import org.w3c.dom.Attr;
28
import org.w3c.dom.Document;
29
import org.w3c.dom.Element;
30
import org.w3c.dom.Node;
31
import org.w3c.dom.NodeList;
32
33
/**
34
 * This class is a utility class for miscellaneous DOM functions, similar to
35
 * org.apache.cocoon.xml.dom.DOMUtil FIXME: Merge classes or extend functionality
36
 */
37
public class DOMUtil {
38
    static Category log = Category.getInstance(DOMUtil.class);
39
40
    DOMParserFactory dpf = null;
41
42
    XPointerFactory xpf = null;
43
44
    /**
45
     * Ctor.
46
     */
47
    public DOMUtil() {
48
        dpf = new DOMParserFactory();
49
        xpf = new XPointerFactory();
50
    }
51
52
    /**
53
     * Main method, used to test the class.
54
     * @param args The command line arguments.
55
     */
56
    public static void main(String[] args) {
57
        try {
58
            DOMUtil du = new DOMUtil();
59
            Document document = du
60
                    .create("<?xml version=\"1.0\"?><Artikel><Datum><Monat Name=\"Juli\"/><Tag>23</Tag></Datum><Content/></Artikel>");
61
            new DOMWriter(System.out).printWithoutFormatting(document);
62
            du.setElementValue(document, "/Artikel/Datum/Tag", "25");
63
            du.setElementValue(document, "/Artikel/Datum/Monat", "7");
64
            du.setElementValue(document, "/Artikel/Datum/Monat", "9");
65
            du.setElementValue(document, "/Artikel/Datm/Mont", "13");
66
            du.setAttributeValue(document, "/Artikel/Datum/Monat/@Name", "Oktober");
67
            du.setAttributeValue(document, "/Artikel/Datu/Monat/@Nam", "August");
68
            du.setElementValue(document, "/Artikel/Datu/Monat", "8");
69
            du.addElement(document, "/Artikel/Datum/Tag", "26");
70
            du.setElementValue(document, "/Artikel/Datum/Tag", "24");
71
72
            new DOMWriter(System.out).printWithoutFormatting(document);
73
            System.out.print("\n");
74
            System.out.print("\n");
75
76
            String[] elements = du.getAllElementValues(document, new XPath("/Artikel/Datum/Monat"));
77
78
            for (int i = 0; i < elements.length; i++) {
79
                System.out.println("Elements=" + elements[i]);
80
            }
81
82
            System.out.print("\n");
83
            System.out.println("Datum/Monat="
84
                    + du.getElementValue(document.getDocumentElement(), new XPath("Datum/Monat")));
85
            System.out.println("Datm="
86
                    + du.getElementValue(document.getDocumentElement(), new XPath("Datm")));
87
88
            System.out.println("Datum/Monat/@Name="
89
                    + du.getAttributeValue(document.getDocumentElement(), new XPath(
90
                            "Datum/Monat/@Name")));
91
        } catch (Exception e) {
92
            System.err.println(e);
93
        }
94
    }
95
96
    /**
97
     * Creates a DOM document from a string.
98
     * 
99
     * @param xml The string.
100
     * @return A DOM document.
101
     * @throws Exception if an error occurs.
102
     * 
103
     * @deprecated Use {@link DocumentHelper#readDocument(java.lang.String)} instead.
104
     */
105
    public Document create(String xml) throws Exception {
106
        return dpf.getDocument(new StringReader(xml));
107
    }
108
109
    /**
110
     * Selects an array of elements using an XPath.
111
     * 
112
     * @param document The document.
113
     * @param xpath The XPath.
114
     * @return An array of elements.
115
     * @throws Exception if the XPath does not return a <code>NodeList</code> consisting of elements.
116
     * 
117
     * @deprecated Use
118
     *             {@link org.apache.xpath.XPathAPI#selectNodeList(org.w3c.dom.Node, java.lang.String)}
119
     *             instead.
120
     */
121
    public Element[] select(Document document, String xpath) throws Exception {
122
        log.debug(".select(): " + xpath);
123
124
        Vector nodes = xpf.select(document, "xpointer(" + xpath + ")");
125
        Element[] elements = new Element[nodes.size()];
126
127
        for (int i = 0; i < nodes.size(); i++) {
128
            elements[i] = (Element) nodes.elementAt(i);
129
        }
130
131
        return elements;
132
    }
133
134
    /**
135
     * <p>
136
     * This method removes all child nodes from an element and inserts a text node instead.
137
     * </p>
138
     * <p>
139
     * Caution: Child elements are removed as well!
140
     * </p>
141
     * @param element The element.
142
     * @param text The string to insert as a text node.
143
     */
144
    public void replaceText(Element element, String text) {
145
        NodeList nl = element.getChildNodes();
146
147
        for (int i = nl.getLength() - 1; i >= 0; i--) {
148
            element.removeChild(nl.item(i));
149
        }
150
151
        element.appendChild(dpf.newTextNode(element.getOwnerDocument(), text));
152
    }
153
154
    /**
155
     * Returns the concatenation string of all text nodes which are children of an element.
156
     * The XPath is resolved against the document element.
157
     * 
158
     * @param document The document.
159
     * @param xpath The XPath of the element to resolve.
160
     * @return A string.
161
     * @throws Exception if an error occurs.
162
     * 
163
     * @deprecated Use {@link DocumentHelper#getSimpleElementText(org.w3c.dom.Element) instead.}
164
     */
165
    public String getElementValue(Document document, XPath xpath) throws Exception {
166
        return getElementValue(document.getDocumentElement(), xpath);
167
    }
168
169
    /**
170
     * Returns the concatenation string of all text nodes which are children of an element.
171
     * The XPath is resolved against a certain element.
172
     * 
173
     * @param element The element to resolve the XPath against.
174
     * @param xpath The XPath of the element to resolve.
175
     * @return A string.
176
     * @throws Exception if an error occurs.
177
     * 
178
     * @deprecated Use {@link DocumentHelper#getSimpleElementText(org.w3c.dom.Element) instead.}
179
     */
180
    public String getElementValue(Element element, XPath xpath) throws Exception {
181
        String value = "";
182
        NodeList nl = getElement(element, xpath).getChildNodes();
183
184
        for (int i = 0; i < nl.getLength(); i++) {
185
            short nodeType = nl.item(i).getNodeType();
186
187
            if (nodeType == Node.TEXT_NODE) {
188
                value = value + nl.item(i).getNodeValue();
189
            } else {
190
                log.warn("XPath " + xpath + " contains node types other than just TEXT_NODE");
191
            }
192
        }
193
194
        return value;
195
    }
196
197
    /**
198
     * Check if elements exists This method just checks the root element! TODO: Implementation is
199
     * not really finished, or is it!
200
     * 
201
     * Replacement code:
202
     * 
203
     * <code>
204
     * Node node = XPathAPI.selectSingleNode(element, xPath);
205
     * if (node != null && node instanceof Element) {
206
     *     exists = true;
207
     * }
208
     * </code>
209
     * 
210
     * @deprecated See replacement code.
211
     */
212
    public boolean elementExists(Element element, XPath xpath) throws Exception {
213
        log.debug(xpath);
214
215
        if (xpath.parts.length > 0) {
216
            NodeList nl = element.getElementsByTagName(xpath.parts[0]);
217
218
            if (nl.getLength() == 0) {
219
                return false;
220
            } else if (nl.getLength() == 1) {
221
                return true;
222
            }
223
        }
224
        return false;
225
    }
226
227
    /**
228
     * Get element via XPath.
229
     * 
230
     * @deprecated Use
231
     *             {@link org.apache.xpath.XPathAPI#selectSingleNode(org.w3c.dom.Node, java.lang.String)}
232
     *             instead.
233
     */
234
    public Element getElement(Element element, XPath xpath) throws Exception {
235
        log.debug(xpath);
236
237
        if (xpath.parts.length > 0) {
238
            NodeList nl = element.getElementsByTagName(xpath.parts[0]);
239
240
            if (nl.getLength() == 0) {
241
                throw new Exception("There are no elements with Name \"" + xpath.parts[0] + "\".");
242
            } else if (nl.getLength() == 1) {
243
                log.debug("There is one element with Name \"" + xpath.parts[0] + "\" ("
244
                        + xpath.parts.length + ").");
245
246
                if (xpath.parts.length == 1) {
247
                    return (Element) nl.item(0);
248
                } else {
249
                    String newXPathString = xpath.parts[1];
250
251
                    for (int i = 2; i < xpath.parts.length; i++) {
252
                        newXPathString = newXPathString + "/" + xpath.parts[i];
253
                    }
254
255
                    return getElement((Element) nl.item(0), new XPath(newXPathString));
256
                }
257
            } else {
258
                throw new Exception("There are more elements than one with Name \""
259
                        + xpath.parts[0] + "\".");
260
            }
261
        }
262
263
        return null;
264
    }
265
266
    /**
267
     * get all elements with |xpath|, xpath has to start with the root node
268
     * 
269
     * @param document a value of type 'Document'
270
     * @param xpath a value of type 'XPath'
271
     * 
272
     * @return a value of type 'Element[]'
273
     * 
274
     * @exception Exception if an error occurs
275
     * 
276
     * @deprecated Use
277
     *             {@link org.apache.xpath.XPathAPI#selectNodeList(org.w3c.dom.Node, java.lang.String)}
278
     *             instead.
279
     */
280
    public Element[] getAllElements(Document document, XPath xpath) throws Exception {
281
        Vector nodes = xpf.select(document.getDocumentElement(), "xpointer(" + xpath.toString()
282
                + ")");
283
        Element[] elements = new Element[nodes.size()];
284
285
        for (int i = 0; i < nodes.size(); i++) {
286
            elements[i] = (Element) nodes.elementAt(i);
287
        }
288
289
        return elements;
290
    }
291
292
    /**
293
     * get all elements values from |xpath|, xpath has to start with the root node
294
     * 
295
     * @param document a value of type 'Document'
296
     * @param xpath a value of type 'XPath'
297
     * 
298
     * @return a value of type 'String[]'
299
     * 
300
     * @exception Exception if an error occurs
301
     */
302
    public String[] getAllElementValues(Document document, XPath xpath) throws Exception {
303
        Vector nodes = xpf.select(document.getDocumentElement(), "xpointer(" + xpath.toString()
304
                + ")");
305
        log.debug("n elements " + nodes.size());
306
307
        String[] values = new String[nodes.size()];
308
309
        for (int i = 0; i < nodes.size(); i++) {
310
            values[i] = getElementValue((Element) nodes.elementAt(i));
311
        }
312
313
        return values;
314
    }
315
316
    /**
317
     * Returns the concatenation string of all text nodes which are children of an element.
318
     * 
319
     * @param element The element.
320
     * @return A string.
321
     * @throws Exception if an error occurs.
322
     * 
323
     * Replacement code:
324
     * 
325
     * <code>
326
     * Element element = (Element) XPathAPI.selectSingleNode(document, xPath);
327
     * String value = DocumentHelper.getSimpleElementText(element, "...");
328
     * </code>
329
     * 
330
     * @deprecated See replacement code.
331
     */
332
    public String getElementValue(Element element) throws Exception {
333
        String value = "";
334
        NodeList nl = element.getChildNodes();
335
336
        for (int i = 0; i < nl.getLength(); i++) {
337
            short nodeType = nl.item(i).getNodeType();
338
339
            if (nodeType == Node.TEXT_NODE) {
340
                value = value + nl.item(i).getNodeValue();
341
            } else {
342
                log.warn("Element " + element.getNodeName()
343
                        + " contains node types other than just TEXT_NODE");
344
            }
345
        }
346
347
        return value;
348
    }
349
350
    /**
351
     * Return the value of an attribte named e.g. "this/myelement/(at)myattribute"
352
     * 
353
     * @param element a value of type 'Element'
354
     * @param xpath a value of type 'XPath'
355
     * 
356
     * @return a value of type 'String'
357
     * 
358
     * Replacement code:
359
     * 
360
     * <code>
361
     * Element element = (Element) XPathAPI.selectSingleNode(document, xPath);
362
     * String value = element.getAttribute("...");
363
     * </code>
364
     * 
365
     * @deprecated See replacement code.
366
     */
367
    public String getAttributeValue(Element element, XPath xpath) throws Exception {
368
        Element el = getElement(element, new XPath(xpath.getElementName()));
369
370
        return el.getAttribute(xpath.getName());
371
    }
372
373
    /**
374
     * Describe 'setElementValue' method here.
375
     * 
376
     * @param document a value of type 'Document'
377
     * @param xpath a value of type 'String'
378
     * @param value a value of type 'String'
379
     * 
380
     * @exception Exception if an error occurs
381
     * 
382
     * Replacement code:
383
     * 
384
     * <code>
385
     * Element element = (Element) XPathAPI.selectSingleNode(document, xPath);
386
     * DocumentHelper.setSimpleElementText(element, "...");
387
     * </code>
388
     * 
389
     * @deprecated See replacement code.
390
     */
391
    public void setElementValue(Document document, String xpath, String value) throws Exception {
392
        Element[] elements = select(document, xpath);
393
394
        if (elements.length >= 1) {
395
            if (elements.length > 1) {
396
                log.warn("There are more elements than one with XPath \"" + xpath
397
                        + "\". The value of the first element will be replaced");
398
            }
399
400
            replaceText(elements[0], value);
401
        } else {
402
            XPath xp = new XPath(xpath);
403
            log.warn("XPath does not exist, but will be created: " + xp);
404
405
            Element element = (Element) createNode(document, xp);
406
            replaceText(element, value);
407
        }
408
    }
409
410
    /**
411
     * Replacement code:
412
     * 
413
     * <code>
414
     * Element parent = (Element) XPathAPI.selectSingleNode(document, xPath);
415
     * Element child = NamespaceHelper.createElement("...", "...");
416
     * parent.appendChild(child);
417
     * </code>
418
     * 
419
     * @deprecated See replacement code.
420
     */
421
    public void addElement(Document document, String xpath, String value) throws Exception {
422
        XPath xp = new XPath(xpath);
423
        Node parent = createNode(document, xp.getParent());
424
        Element element = dpf.newElementNode(document, xp.getName());
425
        parent.appendChild(element);
426
427
        if (value != null) {
428
            element.appendChild(dpf.newTextNode(element.getOwnerDocument(), value));
429
        }
430
    }
431
432
    /**
433
     * Replacement code:
434
     * 
435
     * <code>
436
     * Element element = (Element) XPathAPI.selectSingleNode(document, xPath);
437
     * element.setAttribute("...", "...");
438
     * </code>
439
     * 
440
     * @deprecated See replacement code.
441
     */
442
    public void setAttributeValue(Document document, String xpath, String value) throws Exception {
443
        Vector nodes = xpf.select(document, "xpointer(" + xpath + ")");
444
445
        if (nodes.size() >= 1) {
446
            Attr attribute = (Attr) nodes.elementAt(0);
447
            attribute.setValue(value);
448
        } else {
449
            XPath xp = new XPath(xpath);
450
            log.debug("XPath does not exist, but will be created: " + xp);
451
452
            Attr attribute = (Attr) createNode(document, xp);
453
            attribute.setValue(value);
454
        }
455
    }
456
457
    /**
458
     * <ul>
459
     * <li>If the XPath expression denotes an element, the child nodes of this element are replaced by a single
460
     * text node.</li>
461
     * <li>If the XPath expression denotes an attribute, the attribute value is set.</li>
462
     * <li>Otherwise, an error is logged.</li>
463
     * </ul>
464
     * 
465
     * @param document The document to resolve the XPath against.
466
     * @param xpath The XPath.
467
     * @param value A string.
468
     * @throws Exception if an error occurs.
469
     */
470
    public void setValue(Document document, XPath xpath, String value) throws Exception {
471
        short type = xpath.getType();
472
473
        if (type == Node.ATTRIBUTE_NODE) {
474
            setAttributeValue(document, xpath.toString(), value);
475
        } else if (type == Node.ELEMENT_NODE) {
476
            setElementValue(document, xpath.toString(), value);
477
        } else {
478
            log.error("No such type: " + type);
479
        }
480
    }
481
482
    /**
483
     * Replacement code:
484
     * 
485
     * <code>
486
     * Element parent = XPathAPI.selectSingleNode(...);
487
     * Element child = document.createElementNS("http://...", "...");
488
     * parent.appendChild(child);
489
     * </code>
490
     * 
491
     * @deprecated See replacement code.
492
     */
493
    public Node createNode(Document document, XPath xpath) throws Exception {
494
        log.debug(xpath);
495
496
        Node node = null;
497
        Vector nodes = xpf.select(document, "xpointer(" + xpath + ")");
498
499
        if (nodes.size() >= 1) {
500
            node = (Node) nodes.elementAt(0);
501
        } else {
502
            Node parentNode = createNode(document, xpath.getParent());
503
504
            if (xpath.getType() == Node.ATTRIBUTE_NODE) {
505
                ((Element) parentNode).setAttribute(xpath.getNameWithoutPredicates(), "null");
506
                node = ((Element) parentNode).getAttributeNode(xpath.getNameWithoutPredicates());
507
            } else {
508
                node = dpf.newElementNode(document, xpath.getNameWithoutPredicates());
509
                parentNode.appendChild(node);
510
            }
511
        }
512
513
        return node;
514
    }
515
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/MalformedXPointerException.java (-41 lines)
Lines 1-41 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
/**
23
 * DOCUMENT ME!
24
 */
25
public class MalformedXPointerException extends Exception {
26
    /**
27
     * Creates a new MalformedXPointerException object.
28
     */
29
    public MalformedXPointerException() {
30
        super();
31
    }
32
33
    /**
34
     * Creates a new MalformedXPointerException object.
35
     *
36
     * @param s DOCUMENT ME!
37
     */
38
    public MalformedXPointerException(String s) {
39
        super(s);
40
    }
41
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XMLEncToJavaEnc.java (-105 lines)
Lines 1-105 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.util.Hashtable;
23
24
25
/**
26
 * DOCUMENT ME!
27
 * @deprecated 
28
 */
29
public class XMLEncToJavaEnc extends Hashtable {
30
    private static String DEFAULT_ENCODING = "utf-8";
31
32
    private XMLEncToJavaEnc() {
33
        // JAVA supports a lot more...
34
        // http://www.w3.org/International/O-charset-list.html
35
        //
36
        put("ascii", "ASCII");
37
        put("iso-8859-1", "ISO8859_1"); // Latin 1
38
        put("iso-8859-2", "ISO8859_2"); // Latin 2
39
        put("iso-8859-3", "ISO8859_3");
40
        put("iso-8859-4", "ISO8859_4");
41
        put("iso-8859-5", "ISO8859_5");
42
        put("iso-8859-6", "ISO8859_6");
43
        put("iso-8859-7", "ISO8859_7");
44
        put("iso-8859-8", "ISO8859_8");
45
        put("iso-8859-9", "ISO8859_9");
46
        put("big-5", "Big5"); // Traditional Chinese
47
48
        put("cp-874", "Cp874"); // IBM Thai
49
50
        //put("cp-932",???);
51
        put("cp-950", "Cp950"); // PC Chinese (Hongkong, Taiwan)
52
        put("cp-1250", "Cp1250"); // Windows Eastern Europe
53
        put("cp-1251", "Cp1251"); // Windows Cyrillic
54
        put("cp-1252", "Cp1252"); // Windows Latin 1
55
        put("cp-1253", "Cp1253"); // Windows Greek
56
        put("cp-1255", "Cp1255"); // Windows Hebrew
57
        put("cp-1256", "Cp1256"); // Windows Arabic
58
        put("cp-1257", "Cp1257"); // Windows Baltic
59
        put("cp-1258", "Cp1258"); // Windows Vietnamese
60
        put("euc-jp", "EUC_JP"); // JIS0201, 0208, 0212, EUC Encoding, Japanese
61
        put("euc-kr", "EUC_KR"); // KS C 5601, EUC Encoding, Korean
62
63
        put("iso-2022-jp", "ISO2022JP"); // JIS0201, 0208, 0212, ISO2022 Encoding, Japanese
64
        put("iso-2022-kr", "ISO2022KR"); // ISO 2022 KR, Korean
65
66
        put("koi8-r", "KOI8_R"); // KOI8-R, Russian
67
        put("shift_jis", "SJIS"); // Shift-JIS, Japanese
68
69
        put("utf-8", "UTF8");
70
71
        put("euc-tw", "EUC_TW"); // CNS11643 (Plane 1-3), T. Chinese, EUC encoding
72
        put("x-mac-roman", "MacRoman"); // Macintosh Roman
73
        put("x-mac-ce", "MacCentralEurope"); // Macintosh Latin-2
74
        put("x-mac-greek", "MacGreek"); // Macintosh Greek
75
        put("x-mac-turkish", "MacTurkish"); // Macintosh Turkish
76
        put("x-mac-cyrillic", "MacCyrillic"); // Macintosh Cyrillic
77
    }
78
79
    /**
80
     * DOCUMENT ME!
81
     *
82
     * @param args DOCUMENT ME!
83
     */
84
    public static void main(String[] args) {
85
        System.out.println(XMLEncToJavaEnc.getJava("utf-8"));
86
    }
87
88
    /**
89
     * DOCUMENT ME!
90
     *
91
     * @param xmlencoding DOCUMENT ME!
92
     *
93
     * @return DOCUMENT ME!
94
     */
95
    public static String getJava(String xmlencoding) {
96
97
        try {
98
            return ((String) ((new XMLEncToJavaEnc()).get(xmlencoding.toLowerCase())));
99
        } catch (Exception e) {
100
            System.err.println("Unsupported Encoding; reverting to " + DEFAULT_ENCODING);
101
102
            return DEFAULT_ENCODING;
103
        }
104
    }
105
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/DOMParserFactory.java (-318 lines)
Lines 1-318 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.io.File;
23
import java.io.FileNotFoundException;
24
import java.io.InputStream;
25
import java.io.Reader;
26
import java.util.Properties;
27
28
import org.apache.lenya.xml.parser.Parser;
29
import org.apache.log4j.Category;
30
import org.w3c.dom.CDATASection;
31
import org.w3c.dom.Comment;
32
import org.w3c.dom.Document;
33
import org.w3c.dom.Element;
34
import org.w3c.dom.NamedNodeMap;
35
import org.w3c.dom.Node;
36
import org.w3c.dom.NodeList;
37
import org.w3c.dom.Text;
38
import org.xml.sax.SAXException;
39
40
41
/**
42
 * Utility class for creating DOM documents
43
 * @deprecated replaced by DocumentHelper
44
 */
45
public class DOMParserFactory {
46
    static Category log = Category.getInstance(DOMParserFactory.class);
47
    public Parser parser = null;
48
49
    /**
50
     * Reads the properties and gets the parser
51
     */
52
    public DOMParserFactory() {
53
        Properties properties = new Properties();
54
        String propertiesFileName = "conf.properties";
55
56
        try {
57
            properties.load(DOMParserFactory.class.getResourceAsStream(propertiesFileName));
58
        } catch (Exception e) {
59
            log.fatal(": Failed to load properties from resource: " + propertiesFileName);
60
        }
61
62
        String parserName = properties.getProperty("Parser");
63
64
        if (parserName == null) {
65
            log.fatal(": No Parser specified in " + propertiesFileName);
66
        }
67
68
        try {
69
            Class parserClass = Class.forName(parserName);
70
            parser = (Parser) parserClass.newInstance();
71
        } catch (Exception e) {
72
            log.fatal(": " + e);
73
        }
74
    }
75
76
    /**
77
     * DOCUMENT ME!
78
     *
79
     * @param args DOCUMENT ME!
80
     */
81
    public static void main(String[] args) {
82
        DOMParserFactory dpf = new DOMParserFactory();
83
84
        if (args.length != 1) {
85
            System.out.println("Usage: java " + dpf.getClass().getName() + " example.xml");
86
87
            return;
88
        }
89
90
        Document doc = null;
91
92
        try {
93
            doc = dpf.getDocument(args[0]);
94
        } catch (FileNotFoundException e) {
95
            System.err.println("No such file or directory: " + e.getMessage());
96
97
            return;
98
        } catch (SAXException e) {
99
            System.err.println(e);
100
101
            return;
102
        } catch (Exception e) {
103
            System.err.println(e.getMessage());
104
105
            return;
106
        }
107
    }
108
109
    /**
110
     * DOCUMENT ME!
111
     *
112
     * @param filename DOCUMENT ME!
113
     *
114
     * @return DOCUMENT ME!
115
     *
116
     * @throws FileNotFoundException DOCUMENT ME!
117
     * @throws Exception DOCUMENT ME!
118
     */
119
    public Document getDocument(String filename) throws FileNotFoundException, Exception {
120
        File file = new File(filename);
121
122
        if (!file.exists()) {
123
            log.error("No such file or directory: " + filename);
124
            throw new FileNotFoundException(filename);
125
        }
126
127
        return parser.getDocument(filename);
128
    }
129
130
    /**
131
     * DOCUMENT ME!
132
     *
133
     * @param inputStream DOCUMENT ME!
134
     *
135
     * @return DOCUMENT ME!
136
     *
137
     * @throws Exception DOCUMENT ME!
138
     */
139
    public Document getDocument(InputStream inputStream)
140
        throws Exception {
141
        return parser.getDocument(inputStream);
142
    }
143
144
    /**
145
     * Create a document from a reader.
146
     *
147
     * @param inputStream DOCUMENT ME!
148
     * @return DOCUMENT ME!
149
     * @throws Exception DOCUMENT ME!
150
     */
151
    public Document getDocument(Reader reader) throws Exception {
152
        return parser.getDocument(reader);
153
    }
154
155
    /**
156
     * DOCUMENT ME!
157
     *
158
     * @return DOCUMENT ME!
159
     */
160
    public Document getDocument() {
161
        return parser.getDocument();
162
    }
163
164
    /**
165
     * DOCUMENT ME!
166
     *
167
     * @param document DOCUMENT ME!
168
     * @param name DOCUMENT ME!
169
     *
170
     * @return DOCUMENT ME!
171
     */
172
    public Element newElementNode(Document document, String name) {
173
        return parser.newElementNode(document, name);
174
    }
175
176
    /**
177
     * Creates an element with namespace support.
178
     *
179
     * @param document The owner document.
180
     * @param namespaceUri The namespace URI of the element.
181
     * @param qualifiedName The qualified name of the element.
182
     *
183
     * @return An element.
184
     */
185
    public Element newElementNSNode(Document document, String namespaceUri, String qualifiedName) {
186
        return parser.newElementNSNode(document, namespaceUri, qualifiedName);
187
    }
188
        
189
    /**
190
     * DOCUMENT ME!
191
     *
192
     * @param document DOCUMENT ME!
193
     * @param data DOCUMENT ME!
194
     *
195
     * @return DOCUMENT ME!
196
     */
197
    public Text newTextNode(Document document, String data) {
198
        return parser.newTextNode(document, data);
199
    }
200
201
    /**
202
     * CDATA
203
     *
204
     * @param document DOM document
205
     * @param data Text
206
     *
207
     * @return CDATASection
208
     */
209
    public CDATASection newCDATASection(Document document, String data) {
210
        return parser.newCDATASection(document, data);
211
    }
212
213
    /**
214
     * DOCUMENT ME!
215
     *
216
     * @param document DOCUMENT ME!
217
     * @param data DOCUMENT ME!
218
     *
219
     * @return DOCUMENT ME!
220
     */
221
    public Comment newCommentNode(Document document, String data) {
222
        return parser.newCommentNode(document, data);
223
    }
224
225
    /**
226
     * Clone node, which means copy a node into another document
227
     *
228
     * @param document New document where original nodes shall be attached to
229
     * @param original Original node from original document
230
     * @param deep true means clone also all children
231
     *
232
     * @return New node, which is clone of original node
233
     */
234
    public Node cloneNode(Document document, Node original, boolean deep) {
235
        Node node = null;
236
        short nodeType = original.getNodeType();
237
238
        switch (nodeType) {
239
        case Node.ELEMENT_NODE: {
240
            Element element = newElementNSNode(document, original.getNamespaceURI(), original.getNodeName());
241
            log.debug(".cloneNode(): Clone element: " + original.getNodeName());
242
            NamedNodeMap attributes = original.getAttributes();
243
244
            for (int i = 0; i < attributes.getLength(); i++) {
245
                Node attribute = attributes.item(i);
246
                log.debug(".cloneNode(): LocalName: " + attribute.getLocalName() + ", Prefix: " + attribute.getPrefix() + ", NamespaceURI: " + attribute.getNamespaceURI());
247
                element.setAttributeNS(attribute.getNamespaceURI(), attribute.getNodeName(), attribute.getNodeValue());
248
            }
249
250
            node = element;
251
252
            break;
253
        }
254
255
        case Node.TEXT_NODE: {
256
            Text text = newTextNode(document, original.getNodeValue());
257
258
            node = text;
259
260
            break;
261
        }
262
263
        case Node.CDATA_SECTION_NODE: {
264
            CDATASection cdata = newCDATASection(document, original.getNodeValue());
265
266
            node = cdata;
267
268
            break;
269
        }
270
271
        case Node.COMMENT_NODE: {
272
            Comment comment = newCommentNode(document, original.getNodeValue());
273
274
            node = comment;
275
276
            break;
277
        }
278
279
        default:
280
            log.warn(".cloneNode(): Node type not implemented: " + nodeType);
281
            break;
282
        }
283
284
        if (deep && original.hasChildNodes()) {
285
            NodeList nl = original.getChildNodes();
286
287
            for (int i = 0; i < nl.getLength(); i++) {
288
                node.appendChild(cloneNode(document, nl.item(i), deep));
289
            }
290
        }
291
292
        return node;
293
    }
294
295
    /**
296
     * DOCUMENT ME!
297
     *
298
     * @param document DOCUMENT ME!
299
     * @param element DOCUMENT ME!
300
     * @param value DOCUMENT ME!
301
     */
302
    public void setElementValue(Document document, Element element, String value) {
303
        // remove all child nodes
304
        NodeList nl = element.getChildNodes();
305
306
        for (int i = 0; i < nl.getLength(); i++) {
307
            try {
308
                element.removeChild(nl.item(i));
309
            } catch (Exception e) {
310
                System.err.println("EXCEPTION: " + this.getClass().getName() +
311
                    ".setElementValue(): " + e);
312
            }
313
        }
314
315
        // add a new TextNode for storing the new value
316
        element.appendChild(newTextNode(document, value));
317
    }
318
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XPath.java (-119 lines)
Lines 1-119 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import java.util.StringTokenizer;
23
24
import org.w3c.dom.Node;
25
26
public class XPath {
27
    String xpath = null;
28
    String[] parts = null;
29
30
    /**
31
     *
32
     */
33
    public XPath(String xpath) {
34
        this.xpath = xpath;
35
36
        StringTokenizer st = new StringTokenizer(xpath, "/");
37
        int length = st.countTokens();
38
        parts = new String[length];
39
40
        for (int i = 0; i < length; i++) {
41
            parts[i] = st.nextToken();
42
        }
43
    }
44
45
    /**
46
     *
47
     */
48
    public XPath getParent() {
49
        String parentXPath = "";
50
51
        for (int i = 0; i < (parts.length - 1); i++) {
52
            parentXPath = parentXPath + "/" + parts[i];
53
        }
54
55
        return new XPath(parentXPath);
56
    }
57
58
    /**
59
     *
60
     */
61
    public short getType() {
62
        if (parts[parts.length - 1].indexOf("@") == 0) {
63
            return Node.ATTRIBUTE_NODE;
64
        }
65
66
        return Node.ELEMENT_NODE;
67
    }
68
69
    /**
70
     *
71
     */
72
    public String toString() {
73
        return xpath;
74
    }
75
76
    /**
77
     *
78
     */
79
    public String getName() {
80
        if (getType() == Node.ATTRIBUTE_NODE) {
81
            return parts[parts.length - 1].substring(1);
82
        }
83
84
        return parts[parts.length - 1];
85
    }
86
87
    /**
88
     * Describe 'getName' method here.
89
     *
90
     * @return a value of type 'String'
91
     */
92
    public String getElementName() {
93
        if (getType() == Node.ATTRIBUTE_NODE) {
94
            return parts[parts.length - 2];
95
        }
96
97
        return parts[parts.length - 1];
98
    }
99
100
    /**
101
     *
102
     */
103
    public String getNameWithoutPredicates() {
104
        return removePredicates(getName());
105
    }
106
107
    /**
108
     * Remove predicates (square brackets), http://www.w3.org/TR/xpath
109
     */
110
    public String removePredicates(String s) {
111
        int index = s.indexOf("[");
112
113
        if (index >= 0) {
114
            return s.substring(0, index);
115
        }
116
117
        return s;
118
    }
119
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XLink.java (-92 lines)
Lines 1-92 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
import org.w3c.dom.Attr;
23
import org.w3c.dom.Document;
24
import org.w3c.dom.Element;
25
26
public class XLink {
27
28
    public String type = null;
29
    public String href = null;
30
    public String show = null;
31
    public String name = null;
32
    public Element element = null;
33
34
    public static final String XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
35
    public static final String ATTRIBUTE_HREF = "href";
36
    public static final String ATTRIBUTE_SHOW = "show";
37
    public static final String ATTRIBUTE_TYPE = "type";
38
39
    /**
40
     *
41
     */
42
    public XLink() {
43
        type = "simple";
44
        show = "undefined";
45
    }
46
47
    /**
48
     *
49
     */
50
    public XLink(Element element) {
51
        this();
52
        this.element = element;
53
54
        name = element.getNodeName();
55
56
        Attr hrefAttribute = element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_HREF);
57
        if (hrefAttribute != null) {
58
            href = hrefAttribute.getNodeValue();
59
        }
60
        Attr typeAttribute = element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_TYPE);
61
        if (typeAttribute != null) {
62
            type = typeAttribute.getNodeValue();
63
        }
64
        Attr showAttribute = element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_SHOW);
65
        if (showAttribute != null) {
66
            show = showAttribute.getNodeValue();
67
        }
68
69
    }
70
71
    /**
72
     *
73
     */
74
    public Element getXLink(Document document, DOMParserFactory dpf) {
75
        return (Element) dpf.cloneNode(document, element, true);
76
    }
77
78
    /**
79
     *
80
     */
81
    public String toString() {
82
        return "XLink: type=\""
83
            + type
84
            + "\", href=\""
85
            + href
86
            + "\", show=\""
87
            + show
88
            + "\", name=\""
89
            + name
90
            + "\"";
91
    }
92
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/xpointer/XPointer.java (-43 lines)
Lines 1-43 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml.xpointer;
21
22
import java.util.Vector;
23
24
import org.w3c.dom.Node;
25
26
27
/**
28
 * XPointer interface
29
 */
30
public interface XPointer {
31
	
32
    /**
33
     * DOCUMENT ME!
34
     * 
35
     * @param node DOCUMENT ME!
36
     * @param selectString DOCUMENT ME!
37
     * 
38
     * @return DOCUMENT ME!
39
     *
40
     * @exception Exception ...
41
     */
42
    Vector select(Node node, String selectString, Vector namespaces) throws Exception;
43
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/xpointer/XalanXPointer.java (-132 lines)
Lines 1-132 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml.xpointer;
21
22
import java.util.Vector;
23
24
import org.apache.lenya.xml.DOMParserFactory;
25
import org.apache.log4j.Category;
26
import org.apache.xpath.XPathAPI;
27
import org.w3c.dom.Document;
28
import org.w3c.dom.Element;
29
import org.w3c.dom.Node;
30
import org.w3c.dom.NodeList;
31
32
33
/**
34
 * XPointer implementation
35
 */
36
public class XalanXPointer implements XPointer {
37
    private static Category log = Category.getInstance(XalanXPointer.class);
38
39
    /**
40
     * DOCUMENT ME!
41
     *
42
     * @param args DOCUMENT ME!
43
     */
44
    public static void main(String[] args) {
45
        XPointer xpointer = new XalanXPointer();
46
47
        if (args.length != 2) {
48
            System.err.println("Usage: java " + xpointer.getClass().getName() +
49
                " example.xml \"/Example/People/Person[position() < 2]/Street/@Number\"");
50
51
            return;
52
        }
53
54
        DOMParserFactory dpf = new DOMParserFactory();
55
        Document document = null;
56
57
        try {
58
            document = dpf.getDocument(args[0]);
59
        } catch (Exception e) {
60
            System.err.println(xpointer.getClass().getName() + ".main(): " + e);
61
        }
62
63
        Element root = document.getDocumentElement();
64
        String xpath = args[1];
65
66
        try {
67
            Vector namespaces = new Vector();
68
            Vector nodes = xpointer.select(root, xpath, namespaces);
69
70
            for (int i = 0; i < nodes.size(); i++) {
71
                Node node = (Node) nodes.elementAt(i);
72
                short type = node.getNodeType();
73
74
                if (type == Node.ATTRIBUTE_NODE) {
75
                    System.out.println("Attribute (" + node.getNodeName() + "): " +
76
                        node.getNodeValue());
77
                } else if (type == Node.ELEMENT_NODE) {
78
                    System.out.println("Element (" + node.getNodeName() + "): " +
79
                        node.getFirstChild().getNodeValue());
80
                }
81
            }
82
        } catch (Exception e) {
83
            System.err.println(e);
84
        }
85
    }
86
87
    /**
88
     * Select node by specified XPath
89
     *
90
     * @param node Node to select from
91
     * @param xpath XPath to select nodes
92
     *
93
     * @return Selected nodes
94
     *
95
     * @exception Exception ...
96
     */
97
    public Vector select(Node node, String xpath, Vector namespaces) throws Exception {
98
        NodeList children = node.getChildNodes();
99
100
        log.debug("Select " + xpath + " from node " + node.getNodeName());
101
102
        NodeList nl = null;
103
        if (namespaces.size() > 0) {
104
            org.w3c.dom.Document doc = org.apache.lenya.xml.DocumentHelper.createDocument("", "foo", null);
105
            for (int i = 0; i < namespaces.size(); i++) {
106
                String namespace = (String)namespaces.elementAt(i);
107
                String prefix = namespace.substring(0, namespace.indexOf("="));
108
                String namespaceURI = namespace.substring(namespace.indexOf("=") + 1);
109
                log.debug("Namespace: " + prefix + " " + namespaceURI);
110
111
                doc.getDocumentElement().setAttribute("xmlns:" + prefix, namespaceURI);
112
            }
113
            nl = XPathAPI.selectNodeList(node, xpath, doc.getDocumentElement());
114
        } else {
115
            nl = XPathAPI.selectNodeList(node, xpath);
116
        }
117
118
119
	if (nl != null && nl.getLength() == 0) {
120
            log.info("No such nodes: " + xpath);
121
            return new Vector();
122
        }
123
124
        Vector nodes = new Vector();
125
126
        for (int i = 0; i < nl.getLength(); i++) {
127
            nodes.addElement(nl.item(i));
128
        }
129
130
        return nodes;
131
    }
132
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/xpsconf.properties (-28 lines)
Lines 1-28 Link Here
1
# Copyright 1999-2004 The Apache Software Foundation
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
15
# replace: the XLink will be replaced, embed: the XLink will be included, enclose: the XLink will enclose the returned NodeList
16
Include=replace
17
# Example: xlink:href=class:org.apache.lenya.xps.XPSIncludeHelloWorld
18
JavaZone=class:
19
# DEPRECATED Example: xlink:href=/java/org.apache.lenya.xps.XPSIncludeHelloWorld
20
#JavaZone=/java/
21
# Directory where the XLink Interpreter is caching assembled documents
22
#org.apache.lenya.xps.XLinkInterpreter.cacheFolder=
23
# XML Documents received via HTTP Request will not be cached. Conflict with LastModified. Will be solved in the near future by saving LastModified separately.
24
cacheHTTP=no
25
# Proxy Host
26
proxyHost=@xps.proxy.host@
27
# Proxy Port
28
proxyPort=@xps.proxy.port@
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/xml/XIncludeImpl.java (-603 lines)
Lines 1-603 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.xml;
21
22
23
import java.io.File;
24
import java.io.FileOutputStream;
25
import java.io.IOException;
26
import java.io.InputStream;
27
import java.io.OutputStream;
28
import java.net.URL;
29
import java.util.Properties;
30
import java.util.StringTokenizer;
31
import java.util.Vector;
32
33
import org.apache.lenya.net.ProxyManager;
34
import org.apache.log4j.Category;
35
import org.w3c.dom.Document;
36
import org.w3c.dom.Element;
37
import org.w3c.dom.Node;
38
import org.w3c.dom.NodeList;
39
40
41
/**
42
 * XLink/XInclude Processor (Nesting, Caching, Java, Exceptions)
43
 */
44
public class XIncludeImpl implements XInclude {
45
    static Category log = Category.getInstance(XIncludeImpl.class);
46
    DOMParserFactory dpf = null;
47
    XPointerFactory xpf = null;
48
    Configuration conf = null;
49
    ProxyManager pm = null;
50
    String XPSEXCEPTION_ELEMENT_NAME = "XPSEXCEPTION"; // better would be a namespace xps:XLinkException
51
52
    /**
53
     * Creates a new XIncludeImpl object.
54
     */
55
    public XIncludeImpl() {
56
        dpf = new DOMParserFactory();
57
        xpf = new XPointerFactory();
58
        conf = new Configuration();
59
        pm = new ProxyManager();
60
61
        if ((conf.proxyHost != null) && (conf.proxyPort != null)) {
62
            Properties sp = System.getProperties();
63
            sp.put("proxySet", "true");
64
            sp.put("proxyHost", conf.proxyHost);
65
            sp.put("proxyPort", conf.proxyPort);
66
        }
67
    }
68
69
    /**
70
     * Creates a new XIncludeImpl object.
71
     *
72
     * @param includeoption DOCUMENT ME!
73
     */
74
    public XIncludeImpl(String includeoption) {
75
        this();
76
        conf.INCLUDE = includeoption;
77
    }
78
79
    /**
80
     * DOCUMENT ME!
81
     *
82
     * @param reference DOCUMENT ME!
83
     * @param cocoon DOCUMENT ME!
84
     *
85
     * @return DOCUMENT ME!
86
     */
87
    public Document assemble(String reference, String cocoon) {
88
        File workingDirectory = new File(System.getProperty("user.dir"));
89
        XPSSourceInformation sourceInfo = new XPSSourceInformation("file:" + workingDirectory +
90
                "/dummy.xml", cocoon);
91
        String[] args = new String[1];
92
        args[0] = reference;
93
94
        XPSSourceInformation currentInfo = new XPSSourceInformation(args[0], sourceInfo, cocoon);
95
        deleteFromCache(currentInfo.url);
96
97
        Vector nodes = include(args, sourceInfo);
98
        log.debug(sourceInfo);
99
100
        Node node = (Node) nodes.elementAt(0);
101
102
        return node.getOwnerDocument();
103
    }
104
105
    /**
106
     * Remove file from cache
107
     *
108
     * @param url DOCUMENT ME!
109
     */
110
    public void deleteFromCache(URL url) {
111
        if (conf.cacheFolder != null) {
112
            File cacheFile = getCacheFile(url);
113
114
            if (cacheFile.isFile()) {
115
                log.info(".deleteFromCache(): " + cacheFile.getAbsolutePath());
116
                cacheFile.delete();
117
            } else {
118
                log.warn(".deleteFromCache(): No such file in cache: " +
119
                    cacheFile.getAbsolutePath());
120
            }
121
        }
122
    }
123
124
    /**
125
     * DOCUMENT ME!
126
     *
127
     * @param document DOCUMENT ME!
128
     * @param reference DOCUMENT ME!
129
     * @param cocoon DOCUMENT ME!
130
     *
131
     * @return DOCUMENT ME!
132
     */
133
    public Document assemble(Document document, String reference, String cocoon) {
134
        //return document;
135
        Element root = document.getDocumentElement();
136
        Document assembledDocument = dpf.getDocument();
137
        Element assembledRoot = (Element) dpf.cloneNode(assembledDocument, root, false);
138
        assembledDocument.appendChild(assembledRoot);
139
140
        File workingDirectory = new File(System.getProperty("user.dir"));
141
        XPSSourceInformation sourceInfo = new XPSSourceInformation("file:" + workingDirectory + "/dummy.xml", cocoon);
142
        XPSSourceInformation currentInfo = new XPSSourceInformation(reference, sourceInfo, cocoon);
143
        NodeList nl = root.getChildNodes();
144
145
        for (int i = 0; i < nl.getLength(); i++) {
146
            traverse(assembledRoot, nl.item(i), sourceInfo, currentInfo);
147
        }
148
149
        return assembledDocument;
150
    }
151
152
    /**
153
     * DOCUMENT ME!
154
     *
155
     * @param currentInfo DOCUMENT ME!
156
     *
157
     * @return DOCUMENT ME!
158
     *
159
     * @throws Exception DOCUMENT ME!
160
     */
161
    public InputStream readXML(XPSSourceInformation currentInfo)
162
        throws Exception {
163
        InputStream is = null;
164
        File cacheFile = null;
165
        long originalFileLastModified = 0;
166
167
        String protocol = currentInfo.url.getProtocol();
168
169
        URL url = null;
170
171
        if (conf.cacheFolder != null) // Check cache
172
         {
173
            cacheFile = getCacheFile(currentInfo.url);
174
175
            if (protocol.equals("file")) {
176
                File originalFile = new File(currentInfo.url.getFile());
177
                originalFileLastModified = originalFile.lastModified();
178
            } else if (protocol.equals("http")) {
179
                pm.set(currentInfo.url.getHost()); // install proxy if necessary
180
                originalFileLastModified = currentInfo.url.openConnection().getLastModified();
181
            } else {
182
                log.error("No such protocol: " + protocol);
183
            }
184
185
            if (cacheFile.isFile() && (cacheFile.lastModified() >= originalFileLastModified)) {
186
                // File already exists in cache and is newer than original File
187
                url = new URL("file:" + cacheFile.getAbsolutePath());
188
            } else { // File does not exist in cache
189
                url = new URL(currentInfo.url.toString());
190
            }
191
        } else { // No cache folder specified
192
            url = new URL(currentInfo.url.toString());
193
        }
194
195
        // Read Document
196
        is = url.openStream();
197
198
        return is;
199
    }
200
201
    /**
202
     * DOCUMENT ME!
203
     *
204
     * @param currentInfo DOCUMENT ME!
205
     * @param newDocument DOCUMENT ME!
206
     *
207
     * @return DOCUMENT ME!
208
     */
209
    public boolean tryWritingToCache(XPSSourceInformation currentInfo, Document newDocument) {
210
        File cacheFile = null;
211
212
        if (conf.cacheFolder != null) // Check cache
213
         {
214
            cacheFile = getCacheFile(currentInfo.url);
215
        }
216
217
        if (cacheFile != null) {
218
            String protocol = currentInfo.url.getProtocol();
219
220
            if (!cacheFile.exists()) { // Write "Xlink" to cache
221
222
                return writeToCache(protocol, cacheFile, newDocument);
223
            } else { // cacheFile exists
224
225
                long originalFileLastModified = 0;
226
                String p = currentInfo.url.getProtocol();
227
228
                if (p.equals("file")) {
229
                    File originalFile = new File(currentInfo.url.getFile());
230
                    originalFileLastModified = originalFile.lastModified();
231
                } else if (p.equals("http")) {
232
                    try {
233
                        originalFileLastModified = currentInfo.url.openConnection().getLastModified();
234
                    } catch (IOException e) {
235
                        log.error("originalFileLastModified: " + e);
236
                    }
237
                } else {
238
                    log.error("No such protocol: " + p);
239
                }
240
241
                if (cacheFile.lastModified() < originalFileLastModified) {
242
                    // File in cache is older than original File
243
                    return writeToCache(protocol, cacheFile, newDocument);
244
                }
245
            }
246
        }
247
248
        return false;
249
    }
250
251
    /**
252
     * param args args[0]=url
253
     *
254
     * @param args DOCUMENT ME!
255
     * @param sourceInfo DOCUMENT ME!
256
     *
257
     * @return DOCUMENT ME!
258
     */
259
    public Vector include(String[] args, XPSSourceInformation sourceInfo) {
260
        XPSSourceInformation currentInfo = new XPSSourceInformation(args[0], sourceInfo, sourceInfo.cocoon);
261
262
        sourceInfo.addChild(currentInfo);
263
264
        if (currentInfo.checkLoop(sourceInfo, currentInfo.url)) {
265
            log.warn("Loop detected: " + sourceInfo.url.getFile() + " " + currentInfo.url.getFile());
266
            return null;
267
        }
268
269
        Document document = null;
270
        Vector nodes = new Vector();
271
        Document newDocument = dpf.getDocument();
272
273
        try {
274
            InputStream is = readXML(currentInfo);
275
            document = dpf.getDocument(is);
276
        } catch (Exception e) {
277
            log.warn(e + ", currentInfo: " + currentInfo.url.getFile() + " , sourceInfo: " + sourceInfo.url.getFile());
278
279
            Element newRoot = dpf.newElementNode(newDocument, XPSEXCEPTION_ELEMENT_NAME);
280
            newRoot.appendChild(dpf.newTextNode(newDocument, "" + e));
281
            nodes.addElement(newRoot);
282
283
            return nodes;
284
        }
285
286
        Element root = document.getDocumentElement();
287
        Element newRoot = (Element) dpf.cloneNode(newDocument, root, false);
288
        newDocument.appendChild(newRoot);
289
290
        NodeList nl = root.getChildNodes();
291
292
        for (int i = 0; i < nl.getLength(); i++) {
293
            traverse(newRoot, nl.item(i), sourceInfo, currentInfo);
294
        }
295
296
        boolean writtenToCache = tryWritingToCache(currentInfo, newDocument);
297
298
        if (currentInfo.url.getRef() == null) {
299
            log.debug("No XPointer. Return the root node in order to add the whole document.");
300
            nodes.addElement(newRoot);
301
        } else {
302
            log.debug("XPointer: " + currentInfo.url.getRef());
303
            try {
304
                nodes = xpf.select(newRoot, currentInfo.url.getRef());
305
306
                for (int i = 0; i < nodes.size(); i++) {
307
                    short nodeType = ((Node) nodes.elementAt(i)).getNodeType();
308
309
                    switch (nodeType) {
310
                    case Node.ELEMENT_NODE:
311
                        break;
312
313
                    case Node.ATTRIBUTE_NODE: {
314
                        Node attribute = (Node) nodes.elementAt(i);
315
                        nodes.removeElementAt(i);
316
                        nodes.insertElementAt(dpf.newTextNode(attribute.getOwnerDocument(),
317
                                attribute.getNodeValue()), i);
318
319
                        break;
320
                    }
321
322
                    default: {
323
                        log.error(".include(): Node Type (" + nodeType + ") can't be a child of Element");
324
                        nodes.removeElementAt(i);
325
326
                        break;
327
                    }
328
                    }
329
                }
330
            } catch (Exception e) {
331
                log.error("", e);
332
            }
333
        }
334
335
        return nodes;
336
    }
337
338
    /**
339
     * Traverses recursively and looks for XLinks and includes the returned NodeList
340
     *
341
     * @param newParent DOCUMENT ME!
342
     * @param orgChild DOCUMENT ME!
343
     * @param sourceInfo DOCUMENT ME!
344
     * @param currentInfo DOCUMENT ME!
345
     */
346
    public void traverse(Node newParent, Node orgChild, XPSSourceInformation sourceInfo,
347
        XPSSourceInformation currentInfo) {
348
        Vector newChildren = new Vector();
349
        short nodeType = orgChild.getNodeType();
350
        boolean noXLink = true;
351
352
        switch (nodeType) {
353
        case Node.ELEMENT_NODE: {
354
            XLink xlink = new XLink((Element) orgChild);
355
356
            if (xlink.href == null) {
357
                Element newElement = (Element) dpf.cloneNode(newParent.getOwnerDocument(), orgChild, false);
358
                newChildren.addElement(newElement);
359
            } else {
360
                noXLink = false;
361
                log.debug(".traverse(): xlink:href=\"" + xlink.href + "\"");
362
363
                NodeList nl = processXLink(xlink, (Element) orgChild, currentInfo);
364
365
                for (int i = 0; i < nl.getLength(); i++) {
366
                    newChildren.addElement(dpf.cloneNode(newParent.getOwnerDocument(), nl.item(i), true));
367
                }
368
            }
369
370
            break;
371
        }
372
373
        case Node.COMMENT_NODE: {
374
            newChildren.addElement(dpf.newCommentNode(newParent.getOwnerDocument(), orgChild.getNodeValue()));
375
376
            break;
377
        }
378
379
        case Node.TEXT_NODE: {
380
            newChildren.addElement(dpf.newTextNode(newParent.getOwnerDocument(), orgChild.getNodeValue()));
381
382
            break;
383
        }
384
385
        case Node.CDATA_SECTION_NODE: {
386
            newChildren.addElement(dpf.newCDATASection(newParent.getOwnerDocument(), orgChild.getNodeValue()));
387
388
            break;
389
        }
390
391
        default: {
392
            log.error(".traverse(): Node type not implemented: " + nodeType + " (" + currentInfo.url + ")");
393
            break;
394
        }
395
        }
396
397
        for (int i = 0; i < newChildren.size(); i++) {
398
            newParent.appendChild((Node) newChildren.elementAt(i));
399
        }
400
401
        if (orgChild.hasChildNodes() && noXLink) {
402
            NodeList nl = orgChild.getChildNodes();
403
404
            for (int i = 0; i < nl.getLength(); i++) {
405
                traverse((Node) newChildren.elementAt(0), nl.item(i), sourceInfo, currentInfo);
406
            }
407
        }
408
    }
409
410
    /**
411
     * Process XLink
412
     *
413
     * @param xlink DOCUMENT ME!
414
     * @param orgChild DOCUMENT ME!
415
     * @param currentInfo DOCUMENT ME!
416
     *
417
     * @return DOCUMENT ME!
418
     */
419
    public NodeList processXLink(XLink xlink, Element orgChild, XPSSourceInformation currentInfo) {
420
        NodeList nl = null;
421
422
        // NOTE: if no show attribute is specified, then the value will be set to "undefined"
423
        if (!(xlink.show.equals("embed") || xlink.show.equals("enclose") || xlink.show.equals("replace"))) {
424
            log.warn("No such value of attribute \"show\" implemented: " + xlink.show);
425
            nl = noNodesReturnedFromXLink(xlink);
426
        } else {
427
            Vector args = new Vector();
428
            String includeClassName = includeClassName(xlink.href, args);
429
            String[] arguments = new String[args.size()];
430
431
            for (int i = 0; i < args.size(); i++) {
432
                arguments[i] = (String) args.elementAt(i);
433
                log.debug("Arguments: " + arguments[i]);
434
            }
435
436
            Vector newChildren = null;
437
438
            try {
439
                if (includeClassName.equals(this.getClass().getName())) {
440
                    newChildren = include(arguments, currentInfo);
441
                } else {
442
                    Class includeClass = Class.forName(includeClassName);
443
                    XInclude xpsInclude = (XInclude) includeClass.newInstance();
444
                    newChildren = xpsInclude.include(arguments, currentInfo);
445
                }
446
            } catch (Exception e) {
447
                log.error(".processXLink(): " + e);
448
            }
449
450
            if (newChildren != null) // Returned nodes from XLink
451
             {
452
                if (newChildren.size() > 0) {
453
                    Node firstChild = (Node) newChildren.elementAt(0);
454
                    Document xlinkedDocument = firstChild.getOwnerDocument();
455
                    Element dummyRoot = dpf.newElementNode(xlinkedDocument, "DummyRoot");
456
457
                    if (xlink.show.equals("embed")) {
458
                    //if (conf.INCLUDE.equals("embed")) {
459
                        // WARNING: embed was actually meant to also include the actual xlink, but
460
			//          it was never really implemented and hence led to the misinterpretation of replace
461
			//          Therefore we treat it the same as replace
462
                        //dummyRoot.appendChild(xlink.getXLink(xlinkedDocument, dpf));
463
464
                        for (int i = 0; i < newChildren.size(); i++) {
465
                            dummyRoot.appendChild((Node) newChildren.elementAt(i));
466
                        }
467
		    } else if (xlink.show.equals("replace")) {
468
		    //} else if (conf.INCLUDE.equals("replace")) {
469
                        for (int i = 0; i < newChildren.size(); i++) {
470
                            dummyRoot.appendChild((Node) newChildren.elementAt(i));
471
                        }
472
                    } else if (xlink.show.equals("enclose")) {
473
                    //} else if (conf.INCLUDE.equals("enclose")) {
474
                        Element xlinkCopy = xlink.getXLink(xlinkedDocument, dpf);
475
476
                        for (int i = 0; i < newChildren.size(); i++) {
477
                            xlinkCopy.appendChild((Node) newChildren.elementAt(i));
478
                        }
479
                        dummyRoot.appendChild(xlinkCopy);
480
                    } else {
481
                        log.warn("No such attribute \"show\" or such value of attribute \"show\" implemented");
482
                    }
483
484
                    nl = dummyRoot.getChildNodes();
485
                }
486
            }
487
488
            if (nl == null) {
489
                nl = noNodesReturnedFromXLink(xlink);
490
            }
491
492
            if (nl.getLength() == 0) {
493
                nl = noNodesReturnedFromXLink(xlink);
494
            }
495
        }
496
497
        return nl;
498
    }
499
500
    /**
501
     * DOCUMENT ME!
502
     *
503
     * @param xlink DOCUMENT ME!
504
     *
505
     * @return DOCUMENT ME!
506
     */
507
    public NodeList noNodesReturnedFromXLink(XLink xlink) {
508
        log.warn("No nodes returned from XLink: " + xlink);
509
510
        Document dummyDocument = dpf.getDocument();
511
        Element dummyRoot = dpf.newElementNode(dummyDocument, "DummyRoot");
512
        Element element = xlink.getXLink(dummyDocument, dpf);
513
        dummyRoot.appendChild(element);
514
515
        Element exceptionElement = dpf.newElementNode(dummyDocument, XPSEXCEPTION_ELEMENT_NAME);
516
        exceptionElement.appendChild(dpf.newElementNode(dummyDocument, "NoNodesReturnedFromXLink"));
517
        dummyRoot.appendChild(exceptionElement);
518
519
        return dummyRoot.getChildNodes();
520
    }
521
522
    /**
523
     * DOCUMENT ME!
524
     *
525
     * @param href DOCUMENT ME!
526
     * @param args DOCUMENT ME!
527
     *
528
     * @return DOCUMENT ME!
529
     */
530
    public String includeClassName(String href, Vector args) {
531
        String icn = null;
532
533
        if (href.indexOf(conf.JAVA_ZONE) == 0) {
534
            log.debug(".includeClassName(): java class: " + href);
535
            icn = href.substring(conf.JAVA_ZONE.length(), href.length());
536
537
            StringTokenizer st = new StringTokenizer(icn, "?");
538
            icn = st.nextToken();
539
540
            if (st.countTokens() == 1) {
541
                args.addElement(st.nextToken());
542
            }
543
        } else {
544
            icn = this.getClass().getName();
545
            args.addElement(href);
546
        }
547
548
        log.debug(".includeClassName(): class name: " + icn);
549
550
        return icn;
551
    }
552
553
    /**
554
     * DOCUMENT ME!
555
     *
556
     * @param url DOCUMENT ME!
557
     *
558
     * @return DOCUMENT ME!
559
     */
560
    public File getCacheFile(URL url) {
561
        String cacheFile = null;
562
        String protocol = url.getProtocol();
563
564
        if (protocol.equals("file")) {
565
            cacheFile = protocol + "/" + url.getFile();
566
        } else if (protocol.equals("http")) {
567
            cacheFile = protocol + "/" + url.getHost() + "/" + url.getPort() + "/" + url.getFile();
568
        } else {
569
            log.error("No such protocol: " + protocol);
570
        }
571
572
        return new File(conf.cacheFolder + "/" + cacheFile);
573
    }
574
575
    /**
576
     *
577
     */
578
    public boolean writeToCache(String protocol, File cacheFile, Document newDocument) {
579
        if (protocol.equals("http") && !conf.cacheHTTP) {
580
            // Do not cache HTTP
581
            return false;
582
        }
583
584
        File cacheFileParent = new File(cacheFile.getParent());
585
586
        if (!cacheFileParent.isDirectory()) {
587
            cacheFileParent.mkdirs();
588
        }
589
590
        try {
591
            OutputStream out = new FileOutputStream(cacheFile.getAbsolutePath());
592
593
            new DOMWriter(out, "iso-8859-1").printWithoutFormatting(newDocument);
594
            out.close();
595
596
            return true;
597
        } catch (Exception e) {
598
            log.error(".include(): " + e);
599
        }
600
601
        return false;
602
    }
603
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/cms/cocoon/transformation/IncludeTransformer.java (-98 lines)
Lines 1-98 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.cms.cocoon.transformation;
21
22
import org.apache.avalon.framework.configuration.Configurable;
23
import org.apache.avalon.framework.configuration.Configuration;
24
import org.apache.avalon.framework.configuration.ConfigurationException;
25
import org.apache.cocoon.transformation.AbstractDOMTransformer;
26
import org.apache.cocoon.environment.ObjectModelHelper;
27
import org.apache.cocoon.environment.Request;
28
import org.apache.excalibur.source.Source;
29
import org.w3c.dom.Document;
30
31
32
public class IncludeTransformer extends AbstractDOMTransformer implements Configurable {
33
    private String domain = "127.0.0.1";
34
    private String context = null;
35
    private String publication = null;
36
37
    /**
38
     * DOCUMENT ME!
39
     *
40
     * @param conf DOCUMENT ME!
41
     *
42
     * @throws ConfigurationException DOCUMENT ME!
43
     */
44
    public void configure(Configuration conf) throws ConfigurationException {
45
        if (conf != null) {
46
            publication = conf.getChild("publication").getAttribute("type");
47
            getLogger().debug("PUBLICATION TYPE: " + publication);
48
        } else {
49
            getLogger().error("Configuration is null");
50
        }
51
    }
52
53
	/**
54
	 *  (non-Javadoc)
55
	 * @see org.apache.cocoon.transformation.AbstractDOMTransformer#transform(org.w3c.dom.Document)
56
	 */
57
    protected Document transform(Document doc) {
58
        try {
59
            Source input_source = this.resolver.resolveURI("");
60
            String sitemapPath = input_source.getURI();
61
            getLogger().debug("Absolute SITEMAP Directory: " + sitemapPath);
62
63
            String href = this.parameters.getParameter("href", null);
64
65
            if (href != null) {
66
                getLogger().debug("Parameter href = " + href);
67
            } else {
68
                getLogger().debug("No Parameter");
69
            }
70
71
            Request request = ObjectModelHelper.getRequest(objectModel);
72
73
            String request_uri = request.getRequestURI();
74
            String sitemap_uri = request.getSitemapURI();
75
            getLogger().debug("REQUEST URI: " + request_uri);
76
            getLogger().debug("SITEMAP URI: " + sitemap_uri);
77
78
            context = request.getContextPath();
79
80
            String context_publication = context + "/" + publication;
81
            int port = request.getServerPort();
82
            String cocoon_base_request = "http://" + domain + ":" + port + context_publication;
83
            getLogger().debug("COCOON_BASE_REQUEST: " + cocoon_base_request);
84
85
            if (href != null) {
86
                return new org.apache.lenya.xml.XIncludeImpl().assemble(doc, sitemapPath + href,
87
                    cocoon_base_request);
88
            } else {
89
                return new org.apache.lenya.xml.XIncludeImpl().assemble(doc,
90
                    sitemapPath + sitemap_uri, cocoon_base_request);
91
            }
92
        } catch (Exception e) {
93
            getLogger().error(".transform(): " + e, e);
94
        }
95
96
        return doc;
97
    }
98
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/conf.properties (-19 lines)
Lines 1-19 Link Here
1
# Copyright 1999-2004 The Apache Software Foundation
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
15
org.apache.lenya.net.SMTP.host=mail.apache.org
16
org.apache.lenya.net.SMTP.port=25
17
org.apache.lenya.net.SMTP.domain=apache.org
18
19
org.apache.lenya.net.ProxyManager.configurationPath=org/apache/lenya/net/proxyconf.xml
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/ProxyItem.java (-74 lines)
Lines 1-74 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.net;
21
22
import org.apache.lenya.xml.XPointerFactory;
23
import org.apache.regexp.RE;
24
import org.apache.regexp.RESyntaxException;
25
import org.w3c.dom.Element;
26
27
28
/**
29
 * DOCUMENT ME!
30
 */
31
public class ProxyItem {
32
    RE filter = null;
33
    boolean action = false;
34
35
    /**
36
     * Creates a new ProxyItem object.
37
     *
38
     * @param itemElement DOCUMENT ME!
39
     */
40
    public ProxyItem(Element itemElement) {
41
        XPointerFactory xpf = new XPointerFactory();
42
43
        if (itemElement.getNodeName().equals("include")) {
44
            action = true;
45
        } else {
46
            action = false;
47
        }
48
49
        try {
50
            filter = new RE(xpf.getElementValue(itemElement));
51
        } catch (RESyntaxException e) {
52
            System.err.println(this.getClass().getName() + ": " + e);
53
        }
54
    }
55
56
    /**
57
     * DOCUMENT ME!
58
     *
59
     * @param hostname DOCUMENT ME!
60
     *
61
     * @return DOCUMENT ME!
62
     */
63
    public int check(String hostname) {
64
        if (filter.match(hostname)) {
65
            if (action) {
66
                return 1;
67
            } else {
68
                return -1;
69
            }
70
        } else {
71
            return 0;
72
        }
73
    }
74
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/proxyconf.xml (-31 lines)
Lines 1-31 Link Here
1
<?xml version="1.0"?>
2
<!--
3
  Copyright 1999-2004 The Apache Software Foundation
4
5
  Licensed under the Apache License, Version 2.0 (the "License");
6
  you may not use this file except in compliance with the License.
7
  You may obtain a copy of the License at
8
9
      http://www.apache.org/licenses/LICENSE-2.0
10
11
  Unless required by applicable law or agreed to in writing, software
12
  distributed under the License is distributed on an "AS IS" BASIS,
13
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  See the License for the specific language governing permissions and
15
  limitations under the License.
16
-->
17
18
<conf xmlns:xlink="http://www.w3.org/1999/xlink">
19
<!--
20
	<Proxy host="proxy1.example.com" port="8080">
21
		<include>.*</include>
22
		<exclude>.*\.example\.com</exclude>
23
		<include>www\.example\.com</include>
24
	</Proxy>
25
26
	<Proxy host="proxy2.example.com" port="8888">
27
		<include>.*</include>
28
		<exclude>xps\.example\.com</exclude>
29
	</Proxy>
30
-->
31
</conf>
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/ProxyConf.java (-101 lines)
Lines 1-101 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.net;
21
22
import java.util.Vector;
23
24
import org.apache.lenya.xml.XPointerFactory;
25
import org.w3c.dom.Element;
26
27
28
/**
29
 * DOCUMENT ME!
30
 */
31
public class ProxyConf {
32
    String proxyHost = null;
33
    String proxyPort = null;
34
    Vector items = null;
35
36
    /**
37
     * Creates a new ProxyConf object.
38
     *
39
     * @param proxyElement DOCUMENT ME!
40
     */
41
    public ProxyConf(Element proxyElement) {
42
        try {
43
            items = new Vector();
44
45
            XPointerFactory xpf = new XPointerFactory();
46
47
            proxyHost = proxyElement.getAttribute("host");
48
            proxyPort = proxyElement.getAttribute("port");
49
50
            Vector filterEls = xpf.select(proxyElement, "xpointer(include|exclude)");
51
52
            for (int i = 0; i < filterEls.size(); i++) {
53
                ProxyItem item = new ProxyItem((Element) filterEls.elementAt(i));
54
                items.addElement(item);
55
            }
56
        } catch (Exception e) {
57
            System.err.println(this.getClass().getName() + ": " + e);
58
        }
59
    }
60
61
    /**
62
     * DOCUMENT ME!
63
     *
64
     * @param hostname DOCUMENT ME!
65
     *
66
     * @return DOCUMENT ME!
67
     */
68
    public boolean check(String hostname) {
69
        boolean result = false;
70
71
        for (int i = 0; i < items.size(); i++) {
72
            int ires = ((ProxyItem) items.elementAt(i)).check(hostname);
73
74
            if (ires > 0) {
75
                result = true;
76
            } else if (ires < 0) {
77
                result = false;
78
            }
79
        }
80
81
        return result;
82
    }
83
84
    /**
85
     * DOCUMENT ME!
86
     *
87
     * @return DOCUMENT ME!
88
     */
89
    public String getHostName() {
90
        return proxyHost;
91
    }
92
93
    /**
94
     * DOCUMENT ME!
95
     *
96
     * @return DOCUMENT ME!
97
     */
98
    public String getHostPort() {
99
        return proxyPort;
100
    }
101
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/Configuration.java (-139 lines)
Lines 1-139 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.net;
21
22
import java.net.URL;
23
import java.util.Properties;
24
25
import org.apache.log4j.Category;
26
27
28
/**
29
 * Read configuration
30
 */
31
public class Configuration {
32
    static Category log = Category.getInstance(Configuration.class);
33
    public static final String DEFAULT_CONFIGURATION_FILE = "org/apache/lenya/net/conf.properties";
34
    public static final String DEFAULT_CONFIGURATION_KEY = "lenya.configuration";
35
    public static final String OVERRIDE_DEFAULT_CONFIGURATION_KEY = "override.lenya.configuration";
36
    public String configurationPath = null;
37
    public String smtpHost = null;
38
    public String smtpPort = null;
39
    public String smtpDomain = null;
40
41
    /**
42
     * Creates a new Configuration object.
43
     */
44
    public Configuration() {
45
        getProperties(load());
46
    }
47
48
    /**
49
     * http://www.artima.com/java/answers/Mar2001/messages/164.html export
50
     * CLASSPATH=/home/lenya/src/xps/build/properties:... java
51
     * -Doverride.lenya.configuration=org/apache/lenya/altconf.properties org.apache.lenya.net.Configuration
52
     *
53
     * @param args DOCUMENT ME!
54
     */
55
    public static void main(String[] args) {
56
        Configuration conf = new Configuration();
57
58
        System.out.println("Proxy Manager Configuration Path: " + conf.configurationPath);
59
        System.out.println("SMTP Host: " + conf.smtpHost);
60
        System.out.println("SMTP Port: " + conf.smtpPort);
61
        System.out.println("SMTP Domain: " + conf.smtpDomain);
62
    }
63
64
    /**
65
     * DOCUMENT ME!
66
     *
67
     * @return DOCUMENT ME!
68
     */
69
    public static Properties load() {
70
        String resourcePathRelativeToClasspath = System.getProperty(OVERRIDE_DEFAULT_CONFIGURATION_KEY);
71
72
        if (resourcePathRelativeToClasspath == null) {
73
            resourcePathRelativeToClasspath = System.getProperty(DEFAULT_CONFIGURATION_KEY, DEFAULT_CONFIGURATION_FILE);
74
            log.debug(DEFAULT_CONFIGURATION_KEY + "=" + resourcePathRelativeToClasspath);
75
        } else {
76
            log.debug(OVERRIDE_DEFAULT_CONFIGURATION_KEY + "=" + resourcePathRelativeToClasspath);
77
        }
78
79
        URL url = Configuration.class.getClassLoader().getResource(resourcePathRelativeToClasspath);
80
81
        if (url == null) {
82
            log.error(".load(): Could not find resource on classpath: " + resourcePathRelativeToClasspath);
83
        }
84
85
	log.debug(url);
86
87
        Properties properties = new Properties();
88
89
        try {
90
            properties.load(Configuration.class.getResourceAsStream("conf.properties"));
91
        } catch (Exception e) {
92
            log.error(e);
93
        }
94
95
        return properties;
96
    }
97
98
    /**
99
     * DOCUMENT ME!
100
     *
101
     * @param properties DOCUMENT ME!
102
     */
103
    public void getProperties(Properties properties) {
104
        if (properties != null) {
105
            configurationPath = getProperty(properties, "org.apache.lenya.net.ProxyManager.configurationPath");
106
            smtpHost = getProperty(properties, "org.apache.lenya.net.SMTP.host");
107
            smtpPort = getProperty(properties, "org.apache.lenya.net.SMTP.port");
108
            smtpDomain = getProperty(properties, "org.apache.lenya.net.SMTP.domain");
109
        }
110
    }
111
112
    /**
113
     * DOCUMENT ME!
114
     *
115
     * @param properties DOCUMENT ME!
116
     * @param key DOCUMENT ME!
117
     *
118
     * @return DOCUMENT ME!
119
     */
120
    public String getProperty(Properties properties, String key) {
121
        String value = properties.getProperty(key);
122
123
        if (value != null) {
124
            log.debug(key + "=" + value);
125
126
            return value;
127
        } else {
128
            log.error("No such property: " + key);
129
        }
130
131
        return null;
132
    }
133
134
    /**
135
     * DOCUMENT ME!
136
     */
137
    public static void register() {
138
    }
139
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/net/ProxyManager.java (-164 lines)
Lines 1-164 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.net;
21
22
import java.io.File;
23
import java.util.Properties;
24
import java.util.Vector;
25
26
import org.apache.lenya.xml.DocumentHelper;
27
import org.apache.lenya.xml.XPointerFactory;
28
import org.apache.log4j.Category;
29
import org.w3c.dom.Document;
30
import org.w3c.dom.Element;
31
32
33
/**
34
 * The <code>ProxyManager</code> Class is used to set or unset the java systems proxy settings
35
 * based on the hostname of the host that want to be reached.
36
 */
37
public class ProxyManager {
38
    static Category log = Category.getInstance(ProxyManager.class);
39
    Vector proxies = null;
40
41
    /**
42
     * Creating an instance of ProxyManager without argurments reads the configuration from the
43
     * default configuration file ($XPS_HOME/xml/xps/proxyconf.xml)
44
     */
45
    public ProxyManager() {
46
        log.debug("" + new Configuration().configurationPath);
47
        proxies = readConfig(new Configuration().configurationPath);
48
    }
49
50
    /**
51
     * The <code>ProxyManager</code> is created using the customized <code>conffile</code>
52
     *
53
     * @param conffile configuration file to use
54
     */
55
    public ProxyManager(String conffile) {
56
        proxies = readConfig(conffile);
57
    }
58
59
    /**
60
     * DOCUMENT ME!
61
     *
62
     * @param args DOCUMENT ME!
63
     */
64
    public static void main(String[] args) {
65
        if ((args.length > 2) || (args.length < 1)) {
66
            System.err.println(
67
                "Usage: java org.apache.lenya.net.ProxyManager host [configfile.xml]");
68
69
            return;
70
        }
71
72
        ProxyManager pm = null;
73
74
        if (args.length > 1) {
75
            pm = new ProxyManager(args[1]);
76
        } else {
77
            pm = new ProxyManager();
78
        }
79
80
        if (pm.set(args[0])) {
81
            System.out.println("Proxy set: ");
82
        } else {
83
            System.out.println("No proxy set.");
84
        }
85
    }
86
87
    /**
88
     * Check if one of the configured proxies is appropriate for this host and setup the system
89
     * configuration accordingly.
90
     *
91
     * @param host name of the host the connection should be initiated to
92
     *
93
     * @return DOCUMENT ME!
94
     */
95
    public boolean set(String host) {
96
        Properties sp = System.getProperties();
97
98
        for (int i = 0; i < proxies.size(); i++) {
99
            ProxyConf proxy = (ProxyConf) proxies.elementAt(i);
100
101
            if (proxy.check(host)) {
102
                sp.put("proxySet", "true");
103
                sp.put("proxyHost", proxy.getHostName());
104
                sp.put("proxyPort", proxy.getHostPort());
105
                System.setProperties(sp);
106
107
                return true;
108
            }
109
        }
110
111
        sp.remove("proxySet");
112
        sp.put("proxyHost", "");
113
        sp.put("proxyPort", "");
114
        System.setProperties(sp);
115
116
        return false;
117
    }
118
119
    /**
120
     * Read proxy configuration
121
     *
122
     * @param fname Filename of proxy configuration
123
     *
124
     * @return proxies
125
     */
126
    public Vector readConfig(String fname) {
127
        Document document = null;
128
        File configFile = null;
129
130
        try {
131
	    configFile = new File(new java.net.URI(ProxyManager.class.getClassLoader().getResource(fname).toString()));
132
            if (configFile.exists()) {
133
                document = DocumentHelper.readDocument(configFile);
134
            } else {
135
                log.warn("No such file or directory: " + configFile.getAbsolutePath());
136
                return null;
137
            }
138
        } catch (Exception e) {
139
            log.error(e);
140
            return null;
141
        }
142
143
144
        Vector proxyElements = null;
145
        XPointerFactory xpf = new XPointerFactory();
146
147
        try {
148
            proxyElements = xpf.select(document.getDocumentElement(), "xpointer(/conf/Proxy)");
149
            if (proxyElements.size() == 0) log.info("No proxy defined (" + configFile + ")");
150
        } catch (Exception e) {
151
            log.error(e);
152
            return null;
153
        }
154
155
        Vector proxies = new Vector();
156
        for (int i = 0; i < proxyElements.size(); i++) {
157
            ProxyConf proxy = new ProxyConf((Element) proxyElements.elementAt(i));
158
159
            proxies.addElement(proxy);
160
        }
161
162
        return proxies;
163
    }
164
}
(-)C:/src/lenya-trunk/src/java/org/apache/lenya/util/XPSFileOutputStream.java (-143 lines)
Lines 1-143 Link Here
1
/*
2
 * Copyright  1999-2004 The Apache Software Foundation
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
18
/* $Id$  */
19
20
package org.apache.lenya.util;
21
22
import java.io.File;
23
import java.io.FileDescriptor;
24
import java.io.FileOutputStream;
25
import java.io.IOException;
26
27
import org.apache.avalon.excalibur.io.FileUtil;
28
import org.apache.log4j.Category;
29
30
31
/**
32
 * DOCUMENT ME!
33
 */
34
public class XPSFileOutputStream extends FileOutputStream {
35
    static Category log = Category.getInstance(XPSFileOutputStream.class);
36
    private static final String suffixBase = ".xpstemp";
37
    protected String realFilename = null;
38
    protected String suffix = null;
39
40
    /**
41
     * Creates a new XPSFileOutputStream object.
42
     *
43
     * @param name DOCUMENT ME!
44
     *
45
     * @throws IOException DOCUMENT ME!
46
     */
47
    public XPSFileOutputStream(String name) throws IOException {
48
        super(getTempFilename(name));
49
        setRealFilename(name);
50
    }
51
52
    /**
53
     * Creates a new XPSFileOutputStream object.
54
     *
55
     * @param file DOCUMENT ME!
56
     *
57
     * @throws IOException DOCUMENT ME!
58
     */
59
    public XPSFileOutputStream(File file) throws IOException {
60
        super(getTempFilename(file.getAbsolutePath()));
61
        setRealFilename(file.getAbsolutePath());
62
    }
63
64
    /**
65
     * Creates a new XPSFileOutputStream object.
66
     *
67
     * @param filename DOCUMENT ME!
68
     * @param append DOCUMENT ME!
69
     *
70
     * @throws IOException DOCUMENT ME!
71
     */
72
    public XPSFileOutputStream(String filename, boolean append)
73
        throws IOException {
74
        super(getTempFilename(filename), append);
75
        setRealFilename(filename);
76
    }
77
78
    /**
79
     * We cannot support this version of the constructer because we need to play tricks with the
80
     * filename. There is no filename available when starting with a FileDescriptor.
81
     *
82
     * @param fdObj DOCUMENT ME!
83
     *
84
     * @throws IOException DOCUMENT ME!
85
     */
86
    public XPSFileOutputStream(FileDescriptor fdObj) throws IOException {
87
        super(fdObj);
88
        throw new IOException(
89
            "Constructing an XPSFileOutputStream using a FileDescriptor is not suported because we depend on a filename");
90
    }
91
92
    /**
93
	 * @param realname DOCUMENT ME!
94
	 * @return DOCUMENT ME!
95
	 */
96
	// FIXME: the hashCode() is probably not good enough
97
    //        We need to find a better source of a random
98
    //        string that is available to a static method.
99
    //
100
    protected static String getTempFilename(String realname) {
101
        return realname + XPSFileOutputStream.suffixBase + "." + Runtime.getRuntime().hashCode();
102
    }
103
104
    /**
105
	 * @return DOCUMENT ME!
106
	 */
107
	protected String getRealFilename() {
108
        return this.realFilename;
109
    }
110
111
    /**
112
	 * @param filename DOCUMENT ME!
113
	 */
114
	protected void setRealFilename(String filename) {
115
        this.realFilename = filename;
116
    }
117
118
    /**
119
     * DOCUMENT ME!
120
     *
121
     * @throws IOException DOCUMENT ME!
122
     */
123
    public void close() throws IOException {
124
        super.close();
125
        File temp =  new File(getTempFilename(getRealFilename()));
126
		File file =  new File(getRealFilename());
127
        FileUtil.copyFile(temp, file);
128
        boolean deleted = temp.delete();
129
        if (deleted) {
130
        	log.debug("The temporary file "+temp.getAbsolutePath() +"is deleted");
131
        } else {
132
			log.debug("The temporary file "+temp.getAbsolutePath() +" couldn't be deleted");
133
        }
134
        log.debug(".close(): mv " + getTempFilename(getRealFilename()) + " " + getRealFilename());
135
    }
136
137
    /**
138
     * DOCUMENT ME!
139
     */
140
    public void flush() {
141
        log.debug("flush() called");
142
    }
143
}

Return to bug 33030