List of usage examples for org.xml.sax.helpers AttributesImpl AttributesImpl
public AttributesImpl()
From source file:org.apache.cocoon.generation.TextGenerator.java
/** * Generate XML data./*from w ww . j av a 2 s.c om*/ * * @throws IOException * @throws ProcessingException * @throws SAXException */ public void generate() throws IOException, SAXException, ProcessingException { InputStreamReader in = null; try { final InputStream sis = this.inputSource.getInputStream(); if (sis == null) { throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found"); } if (encoding != null) { in = new InputStreamReader(sis, encoding); } else { in = new InputStreamReader(sis); } } catch (SourceException se) { throw new ProcessingException("Error during resolving of '" + this.source + "'.", se); } LocatorImpl locator = new LocatorImpl(); locator.setSystemId(this.inputSource.getURI()); locator.setLineNumber(1); locator.setColumnNumber(1); contentHandler.setDocumentLocator(locator); contentHandler.startDocument(); contentHandler.startPrefixMapping("", URI); AttributesImpl atts = new AttributesImpl(); if (localizable) { atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId()); atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber())); atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber())); } contentHandler.startElement(URI, "text", "text", atts); LineNumberReader reader = new LineNumberReader(in); String line; String newline = null; while (true) { if (newline == null) { line = convertNonXmlChars(reader.readLine()); } else { line = newline; } if (line == null) { break; } newline = convertNonXmlChars(reader.readLine()); if (newline != null) { line += SystemUtils.LINE_SEPARATOR; } locator.setLineNumber(reader.getLineNumber()); locator.setColumnNumber(1); contentHandler.characters(line.toCharArray(), 0, line.length()); if (newline == null) { break; } } reader.close(); contentHandler.endElement(URI, "text", "text"); contentHandler.endPrefixMapping(""); contentHandler.endDocument(); }
From source file:org.apache.cocoon.generation.TextGenerator2.java
/** * Generate XML data./*from w ww . ja va 2 s. c om*/ * * @throws IOException * @throws ProcessingException * @throws SAXException */ public void generate() throws IOException, SAXException, ProcessingException { InputStreamReader in = null; try { final InputStream sis = this.inputSource.getInputStream(); if (sis == null) { throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found"); } if (encoding != null) { in = new InputStreamReader(sis, encoding); } else { in = new InputStreamReader(sis); } } catch (SourceException se) { throw new ProcessingException("Error during resolving of '" + this.source + "'.", se); } LocatorImpl locator = new LocatorImpl(); locator.setSystemId(this.inputSource.getURI()); locator.setLineNumber(1); locator.setColumnNumber(1); /* Do not pass the source URI to the contentHandler, assuming that that is the LexicalTransformer. It does not have to be. contentHandler.setDocumentLocator(locator); */ contentHandler.startDocument(); AttributesImpl atts = new AttributesImpl(); if (localizable) { atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId()); atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber())); atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber())); } String nsPrefix = this.element.contains(":") ? this.element.replaceFirst(":.+$", "") : ""; String localName = this.element.replaceFirst("^.+:", ""); if (this.namespace.length() > 1) contentHandler.startPrefixMapping(nsPrefix, this.namespace); contentHandler.startElement(this.namespace, localName, this.element, atts); LineNumberReader reader = new LineNumberReader(in); String line; String newline = null; while (true) { if (newline == null) { line = convertNonXmlChars(reader.readLine()); } else { line = newline; } if (line == null) { break; } newline = convertNonXmlChars(reader.readLine()); if (newline != null) { line += SystemUtils.LINE_SEPARATOR; } locator.setLineNumber(reader.getLineNumber()); locator.setColumnNumber(1); contentHandler.characters(line.toCharArray(), 0, line.length()); if (newline == null) { break; } } reader.close(); contentHandler.endElement(this.namespace, localName, this.element); if (this.namespace.length() > 1) contentHandler.endPrefixMapping(nsPrefix); contentHandler.endDocument(); }
From source file:org.apache.cocoon.generation.XPathDirectoryGenerator.java
/** * Performs an XPath query on the file./*w w w .j av a 2s.c o m*/ * * @param xmlFile the File the XPath is performed on. * * @throws SAXException if something goes wrong while adding the XML snippet. */ protected void performXPathQuery(File xmlFile) throws SAXException { this.doc = null; Source source = null; try { source = resolver.resolveURI(xmlFile.toURL().toExternalForm()); this.doc = this.parser.parseDocument(SourceUtil.getInputSource(source)); } catch (SAXException e) { getLogger().error("Warning:" + xmlFile.getName() + " is not a valid XML file. Ignoring.", e); } catch (ProcessingException e) { getLogger().error("Warning: Problem while reading the file " + xmlFile.getName() + ". Ignoring.", e); } catch (IOException e) { getLogger().error("Warning: Problem while reading the file " + xmlFile.getName() + ". Ignoring.", e); } finally { resolver.release(source); } if (doc != null) { NodeList nl = (null == this.prefixResolver) ? this.processor.selectNodeList(this.doc.getDocumentElement(), this.xpath) : this.processor.selectNodeList(this.doc.getDocumentElement(), this.xpath, this.prefixResolver); AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", QUERY_ATTR_NAME, QUERY_ATTR_NAME, "CDATA", xpath); super.contentHandler.startElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME, attributes); DOMStreamer ds = new DOMStreamer(super.xmlConsumer); for (int i = 0; i < nl.getLength(); i++) { ds.stream(nl.item(i)); } super.contentHandler.endElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME); } }
From source file:org.apache.cocoon.generation.XPathTraversableGenerator.java
/** * Performs an XPath query on the source. * @param in the Source the XPath is performed on. * @throws SAXException if something goes wrong while adding the XML snippet. *//* w w w . j a v a2 s .com*/ protected void performXPathQuery(TraversableSource in) throws SAXException { doc = null; try { doc = this.parser.parseDocument(SourceUtil.getInputSource(in)); } catch (SAXException se) { getLogger().error("Warning:" + in.getName() + " is not a valid XML document. Ignoring"); } catch (Exception e) { this.getLogger().error("Unable to resolve and parse document" + e); } if (doc != null) { NodeList nl = processor.selectNodeList(doc.getDocumentElement(), xpath, this.prefixResolver); final String id = in.getName(); AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", RESULT_DOCID_ATTR, RESULT_DOCID_ATTR, " CDATA", id); attributes.addAttribute("", QUERY_ATTR_NAME, QUERY_ATTR_NAME, "CDATA", xpath); super.contentHandler.startElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME, attributes); DOMStreamer ds = new DOMStreamer(super.xmlConsumer); for (int i = 0; i < nl.getLength(); i++) { ds.stream(nl.item(i)); } super.contentHandler.endElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME); } }
From source file:org.apache.cocoon.transformation.DASLTransformer.java
protected void performSearchMethod(String query) throws SAXException { OptionsMethod optionsMethod = null;/* w w w.j a va2 s.co m*/ SearchMethod searchMethod = null; try { DOMStreamer propertyStreamer = new DOMStreamer(this.xmlConsumer); optionsMethod = new OptionsMethod(this.targetUrl); searchMethod = new SearchMethod(this.targetUrl, query); HttpURL url = new HttpURL(this.targetUrl); HttpState state = new HttpState(); state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword())); HttpConnection conn = new HttpConnection(url.getHost(), url.getPort()); // eventcaching stuff SourceValidity extraValidity = makeWebdavEventValidity(url); if (extraValidity != null && m_validity != null) m_validity.add(extraValidity); // end eventcaching stuff WebdavResource resource = new WebdavResource(new HttpURL(this.targetUrl)); if (!resource.exists()) { throw new SAXException("The WebDAV resource don't exist"); } optionsMethod.execute(state, conn); if (!optionsMethod.isAllowed("SEARCH")) { throw new SAXException("The server doesn't support the SEARCH method"); } int httpstatus = searchMethod.execute(state, conn); this.contentHandler.startElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG, XMLUtils.EMPTY_ATTRIBUTES); // something might have gone wrong, report it // 207 = multistatus webdav response if (httpstatus != 207) { this.contentHandler.startElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG, XMLUtils.EMPTY_ATTRIBUTES); // dump whatever the server said propertyStreamer.stream(searchMethod.getResponseDocument()); this.contentHandler.endElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG); } else { // show results Enumeration enumeration = searchMethod.getAllResponseURLs(); while (enumeration.hasMoreElements()) { String path = (String) enumeration.nextElement(); Enumeration properties = searchMethod.getResponseProperties(path); AttributesImpl attr = new AttributesImpl(); attr.addAttribute(DASL_QUERY_NS, PATH_NODE_NAME, PREFIX + ":" + PATH_NODE_NAME, "CDATA", path); this.contentHandler.startElement(DASL_QUERY_NS, RESOURCE_NODE_NAME, PREFIX + ":" + RESOURCE_NODE_NAME, attr); while (properties.hasMoreElements()) { BaseProperty metadata = (BaseProperty) properties.nextElement(); Element propertyElement = metadata.getElement(); propertyStreamer.stream(propertyElement); } this.contentHandler.endElement(DASL_QUERY_NS, RESOURCE_NODE_NAME, PREFIX + ":" + RESOURCE_NODE_NAME); } } this.contentHandler.endElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG); } catch (SAXException e) { throw new SAXException("Unable to fetch the query data:", e); } catch (HttpException e1) { this.getLogger().error("Unable to contact Webdav server", e1); throw new SAXException("Unable to connect with server: ", e1); } catch (IOException e2) { throw new SAXException("Unable to connect with server: ", e2); } catch (NullPointerException e) { throw new SAXException("Unable to fetch the query data:", e); } catch (Exception e) { throw new SAXException("Generic Error:", e); } finally { // cleanup if (searchMethod != null) searchMethod.releaseConnection(); if (optionsMethod != null) optionsMethod.releaseConnection(); } }
From source file:org.apache.cocoon.transformation.PatternTransformer.java
/** * @throws SAXException/*from ww w. j av a 2 s . co m*/ */ private void search() throws SAXException { if (buffer.length() <= 0) return; char[] text = buffer.toString().toCharArray(); String lexemesymbol; String lexemetext; String[] groups = null; int lexemeindex = 0; int position = 0; output.setLength(0); do { lexemesymbol = null; lexemetext = null; for (lexemeindex = automaton.getLexemeCount() - 1; lexemeindex >= 0; lexemeindex--) { processor.setPatternAutomaton(automaton.getLexemeDefinition(lexemeindex)); if ((processor.match(text, position)) && ((lexemetext == null) || (processor.getGroup().length() >= lexemetext.length()))) { lexemesymbol = automaton.getLexemeSymbol(lexemeindex); lexemetext = processor.getGroup(); if (this.groups) { groups = new String[processor.getGroupCount()]; for (int group = 0; group < processor.getGroupCount(); group++) groups[group] = processor.getGroup(group); } } } if ((lexemetext != null) && (lexemetext.length() > 0)) { if (lexemesymbol != null) { if (logger != null) logger.debug("Recognize token " + lexemesymbol + " with " + Decoder.toString(lexemetext)); if (output.length() > 0) contentHandler.characters(output.toString().toCharArray(), 0, output.length()); output.setLength(0); contentHandler.startPrefixMapping("", NS); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "symbol", "symbol", "CDATA", lexemesymbol); atts.addAttribute("", "text", "text", "CDATA", lexemetext); contentHandler.startElement(NS, "lexeme", "lexeme", atts); if (this.groups) { for (int group = 0; group < groups.length; group++) { contentHandler.startElement(NS, "group", "group", XMLUtils.EMPTY_ATTRIBUTES); contentHandler.characters(groups[group].toCharArray(), 0, groups[group].length()); contentHandler.endElement(NS, "group", "group"); } } contentHandler.endElement(NS, "lexeme", "lexeme"); contentHandler.endPrefixMapping(""); } else if (logger != null) logger.debug("Ignore lexeme with " + Decoder.toString(lexemetext)); position += lexemetext.length(); } else { output.append(text[position]); position++; } } while (position < text.length); if (output.length() > 0) contentHandler.characters(output.toString().toCharArray(), 0, output.length()); buffer.setLength(0); }
From source file:org.apache.fop.events.model.EventModel.java
/** {@inheritDoc} */ public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String elName = "event-model"; handler.startElement("", elName, elName, atts); Iterator iter = getProducers(); while (iter.hasNext()) { ((XMLizable) iter.next()).toSAX(handler); }/*from ww w . ja va 2s . co m*/ handler.endElement("", elName, elName); }
From source file:org.apache.fop.render.svg.EmbeddedSVGImageHandler.java
/** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext) context; ImageXMLDOM svg = (ImageXMLDOM) image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try {//w w w.j a v a2 s .com Document doc = (Document) svg.getDocument(); Element svgEl = (Element) doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
From source file:org.apache.fop.render.svg.SVGDataUrlImageHandler.java
/** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext) context; ImageRawStream raw = (ImageRawStream) image; InputStream in = raw.createInputStream(); try {/*w ww.ja va2s . co m*/ ContentHandler handler = svgContext.getContentHandler(); String url = DataURLUtil.createDataURL(in, raw.getMimeType()); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, IFConstants.XLINK_HREF, url); atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x)); atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y)); atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width)); atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height)); try { handler.startElement(NAMESPACE, "image", "image", atts); handler.endElement(NAMESPACE, "image", "image"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); } }
From source file:org.apache.fop.render.svg.SVGDocumentHandler.java
/** {@inheritDoc} */ public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { if (this.multiFileUtil != null) { prepareHandlerWithOutputStream(index); } else {//from w ww . ja v a 2 s . c o m if (this.simpleResult == null) { //Only one page is supported with this approach at the moment throw new IFException("Only one page is supported for output with the given Result instance!", null); } super.setResult(this.simpleResult); this.simpleResult = null; } try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1 /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt"); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt"); XMLUtil.addAttribute(atts, "viewBox", "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height)); handler.startElement("svg", atts); try { Transformer transformer = tFactory.newTransformer(); Source src = new DOMSource(this.reusedParts.getDocumentElement()); Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler)); transformer.transform(src, res); } catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); } catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException) te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } } } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }