01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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: package org.apache.cocoon.components.xpointer;
18:
19: import org.apache.avalon.framework.service.ServiceManager;
20: import org.apache.cocoon.xml.XMLConsumer;
21: import org.apache.cocoon.xml.dom.DOMStreamer;
22: import org.apache.cocoon.ResourceNotFoundException;
23: import org.apache.excalibur.xml.xpath.XPathProcessor;
24: import org.w3c.dom.Document;
25: import org.w3c.dom.NodeList;
26: import org.xml.sax.SAXException;
27: import org.xml.sax.helpers.LocatorImpl;
28:
29: /**
30: * Partly implementation of the xpointer() scheme. Only the XPath subset of xpointer is supported.
31: */
32: public class XPointerPart implements PointerPart {
33: private String expression;
34:
35: public XPointerPart(String expression) {
36: this .expression = expression;
37: }
38:
39: public boolean process(XPointerContext xpointerContext)
40: throws SAXException, ResourceNotFoundException {
41: Document document = xpointerContext.getDocument();
42: ServiceManager manager = xpointerContext.getServiceManager();
43: XPathProcessor xpathProcessor = null;
44: try {
45: try {
46: xpathProcessor = (XPathProcessor) manager
47: .lookup(XPathProcessor.ROLE);
48: } catch (Exception e) {
49: throw new SAXException(
50: "XPointerPart: error looking up XPathProcessor.",
51: e);
52: }
53: NodeList nodeList = xpathProcessor.selectNodeList(document,
54: expression, xpointerContext);
55: if (nodeList.getLength() > 0) {
56: XMLConsumer consumer = xpointerContext.getXmlConsumer();
57: LocatorImpl locator = new LocatorImpl();
58: locator.setSystemId(xpointerContext.getSource()
59: .getURI());
60: consumer.setDocumentLocator(locator);
61: for (int i = 0; i < nodeList.getLength(); i++) {
62: DOMStreamer streamer = new DOMStreamer();
63: streamer.setConsumer(consumer);
64: streamer.stream(nodeList.item(i));
65: }
66: return true;
67: } else {
68: if (xpointerContext.getLogger().isDebugEnabled())
69: xpointerContext.getLogger().debug(
70: "XPointer: expression \"" + expression
71: + "\" gave no results.");
72: return false;
73: }
74: } finally {
75: if (xpathProcessor != null)
76: manager.release(xpathProcessor);
77: }
78: }
79: }
|