List of usage examples for org.xml.sax XMLReader setContentHandler
public void setContentHandler(ContentHandler handler);
From source file:org.springframework.oxm.xmlbeans.XmlBeansMarshaller.java
@Override protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) throws XmlMappingException, IOException { XmlSaxHandler saxHandler = XmlObject.Factory.newXmlSaxHandler(getXmlOptions()); xmlReader.setContentHandler(saxHandler.getContentHandler()); try {// w ww.ja v a 2s . c o m xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", saxHandler.getLexicalHandler()); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { // ignore } try { xmlReader.parse(inputSource); XmlObject object = saxHandler.getObject(); validate(object); return object; } catch (SAXException ex) { throw convertXmlBeansException(ex, false); } catch (XmlException ex) { throw convertXmlBeansException(ex, false); } }
From source file:org.tinymediamanager.thirdparty.UpnpDevice.java
/** * Retrieves the properties and description of the UpnpDevice. * <p/>//from w ww .ja v a 2 s .c o m * Connects to the device's {@link #location} and parses the response to populate the fields of this class * * @throws SAXException * if an error occurs while parsing the request * @throws IOException * on communication errors * @see org.bitlet.weupnp.GatewayDeviceHandler */ public void loadDescription() throws SAXException, IOException { URLConnection urlConn = new URL(getLocation()).openConnection(); urlConn.setReadTimeout(HTTP_RECEIVE_TIMEOUT); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new UpnpDeviceHandler(this)); parser.parse(new InputSource(urlConn.getInputStream())); /* fix urls */ String ipConDescURL; if (urlBase != null && urlBase.trim().length() > 0) { ipConDescURL = urlBase; } else { ipConDescURL = location; } int lastSlashIndex = ipConDescURL.indexOf('/', 7); if (lastSlashIndex > 0) { ipConDescURL = ipConDescURL.substring(0, lastSlashIndex); } sCPDURL = copyOrCatUrl(ipConDescURL, sCPDURL); controlURL = copyOrCatUrl(ipConDescURL, controlURL); controlURLCIF = copyOrCatUrl(ipConDescURL, controlURLCIF); presentationURL = copyOrCatUrl(ipConDescURL, presentationURL); }
From source file:org.toobsframework.transformpipeline.domain.BaseXMLTransformer.java
protected Templates getTemplates(String xsl, XMLReader reader) throws TransformerConfigurationException, TransformerException, IOException, SAXException { Templates templates = null;/* w ww . j av a2 s. c om*/ if (templateCache.containsKey(xsl) && !doReload) { templates = templateCache.get(xsl); } else { // Get an XMLReader. if (reader == null) { reader = XMLReaderManager.getInstance().getXMLReader(); } TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler(); reader.setContentHandler(templatesHandler); try { reader.parse(getInputSource(xsl)); } catch (MalformedURLException e) { log.info("Xerces Version: " + Version.getVersion()); throw e; } templates = templatesHandler.getTemplates(); templateCache.put(xsl, templates); } return templates; }
From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransformer.java
private String transform(List inputXSLs, String inputXML, Map inputParams, IXMLTransformerHelper transformerHelper) throws XMLTransformerException { String outputXML = null;/* ww w. ja v a 2 s .c o m*/ ByteArrayInputStream xmlInputStream = null; ByteArrayOutputStream xmlOutputStream = null; try { TransformerFactory tFactory = TransformerFactory.newInstance(); setFactoryResolver(tFactory); if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a TransformerHandler for each stylesheet. ArrayList tHandlers = new ArrayList(); TransformerHandler tHandler = null; // Create an XMLReader. XMLReader reader = new SAXParser(); // transformer3 outputs SAX events to the serializer. if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } Serializer serializer = SerializerFactory.getSerializer(outputProperties); String xslFile = null; for (int it = 0; it < inputXSLs.size(); it++) { Object source = inputXSLs.get(it); if (source instanceof StreamSource) { tHandler = saxTFactory.newTransformerHandler((StreamSource) source); if (xslFile == null) xslFile = ((StreamSource) source).getSystemId(); } else { //tHandler = saxTFactory.newTransformerHandler(new StreamSource(getXSLFile((String) source))); tHandler = saxTFactory .newTransformerHandler(uriResolver.resolve((String) source + ".xsl", "")); if (xslFile == null) xslFile = (String) source; } Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty("encoding", "UTF-8"); transformer.setErrorListener(tFactory.getErrorListener()); if (inputParams != null) { Iterator paramIt = inputParams.entrySet().iterator(); while (paramIt.hasNext()) { Map.Entry thisParam = (Map.Entry) paramIt.next(); transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue()); } } if (transformerHelper != null) { transformer.setParameter(TRANSFORMER_HELPER, transformerHelper); } tHandlers.add(tHandler); } tHandler = null; for (int th = 0; th < tHandlers.size(); th++) { tHandler = (TransformerHandler) tHandlers.get(th); if (th == 0) { reader.setContentHandler(tHandler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler); } else { ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler)); } } // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. InputSource xmlSource = null; xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8")); if (log.isTraceEnabled()) { log.trace("Input XML:\n" + inputXML); } xmlSource = new InputSource(xmlInputStream); xmlOutputStream = new ByteArrayOutputStream(); serializer.setOutputStream(xmlOutputStream); ((TransformerHandler) tHandlers.get(tHandlers.size() - 1)) .setResult(new SAXResult(serializer.asContentHandler())); Date timer = new Date(); reader.parse(xmlSource); Date timer2 = new Date(); outputXML = xmlOutputStream.toString("UTF-8"); if (log.isDebugEnabled()) { long diff = timer2.getTime() - timer.getTime(); log.debug("Time to transform: " + diff + " mS XSL: " + xslFile); if (log.isTraceEnabled()) { log.trace("Output XML:\n" + outputXML); } } } } catch (IOException ex) { throw new XMLTransformerException(ex); } catch (IllegalArgumentException ex) { throw new XMLTransformerException(ex); } catch (SAXException ex) { throw new XMLTransformerException(ex); } catch (TransformerConfigurationException ex) { throw new XMLTransformerException(ex); } catch (TransformerFactoryConfigurationError ex) { throw new XMLTransformerException(ex); } catch (TransformerException ex) { throw new XMLTransformerException(ex); } finally { try { if (xmlInputStream != null) { xmlInputStream.close(); xmlInputStream = null; } if (xmlOutputStream != null) { xmlOutputStream.close(); xmlOutputStream = null; } } catch (IOException ex) { } } return outputXML; }
From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransletTransformer.java
public String transform(List inputXSLs, String inputXML, Map inputParams, IXMLTransformerHelper transformerHelper) throws XMLTransformerException { String outputXML = null;//from w w w .j a va2 s . c o m ByteArrayInputStream xmlInputStream = null; ByteArrayOutputStream xmlOutputStream = null; try { TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl(); try { //tFactory.setAttribute("use-classpath", Boolean.TRUE); tFactory.setAttribute("auto-translet", Boolean.TRUE); } catch (IllegalArgumentException iae) { log.error("Error setting XSLTC specific attribute", iae); throw new XMLTransformerException(iae); } setFactoryResolver(tFactory); TransformerFactoryImpl traxFactory = (TransformerFactoryImpl) tFactory; // Create a TransformerHandler for each stylesheet. ArrayList tHandlers = new ArrayList(); TransformerHandler tHandler = null; // Create a SAX XMLReader. XMLReader reader = new org.apache.xerces.parsers.SAXParser(); // transformer3 outputs SAX events to the serializer. if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } Serializer serializer = SerializerFactory.getSerializer(outputProperties); for (int it = 0; it < inputXSLs.size(); it++) { String xslTranslet = (String) inputXSLs.get(it); Source source = uriResolver.resolve(xslTranslet + ".xsl", ""); String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/")) .replaceAll("/", ".").replaceAll("-", "_"); // Package name needs to be set for each TransformerHandler instance tFactory.setAttribute("package-name", tPkg); tHandler = traxFactory.newTransformerHandler(source); // Set parameters and output encoding on each handlers transformer Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty("encoding", "UTF-8"); transformer.setErrorListener(tFactory.getErrorListener()); if (inputParams != null) { Iterator paramIt = inputParams.entrySet().iterator(); while (paramIt.hasNext()) { Map.Entry thisParam = (Map.Entry) paramIt.next(); transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue()); } } if (transformerHelper != null) { transformer.setParameter(TRANSFORMER_HELPER, transformerHelper); } tHandlers.add(tHandler); } tHandler = null; // Link the handlers to each other and to the reader for (int th = 0; th < tHandlers.size(); th++) { tHandler = (TransformerHandler) tHandlers.get(th); if (th == 0) { reader.setContentHandler(tHandler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler); } else { ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler)); } } // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. InputSource xmlSource = null; xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8")); xmlSource = new InputSource(xmlInputStream); xmlOutputStream = new ByteArrayOutputStream(); serializer.setOutputStream(xmlOutputStream); // Link the last handler to the serializer ((TransformerHandler) tHandlers.get(tHandlers.size() - 1)) .setResult(new SAXResult(serializer.asContentHandler())); reader.parse(xmlSource); outputXML = xmlOutputStream.toString("UTF-8"); } catch (Exception ex) { log.error("Error performing chained transformation: " + ex.getMessage(), ex); throw new XMLTransformerException(ex); } finally { try { if (xmlInputStream != null) { xmlInputStream.close(); xmlInputStream = null; } if (xmlOutputStream != null) { xmlOutputStream.close(); xmlOutputStream = null; } } catch (IOException ex) { } } return outputXML; }
From source file:org.unitils.dbunit.datasetfactory.impl.MultiSchemaXmlDataSetFactory.java
/** * Parses the data sets from the given files. * Each schema is given its own data set and each row is given its own table. * * @param dataSetFiles The data set files, not null * @return The read data set, not null//w w w. j a v a 2 s. c om */ public MultiSchemaDataSet createDataSet(List<File> dataSetFiles) { DataSetContentHandler dataSetContentHandler = new DataSetContentHandler(defaultSchemaName); XMLReader xmlReader = createXMLReader(); xmlReader.setContentHandler(dataSetContentHandler); xmlReader.setErrorHandler(dataSetContentHandler); for (File dataSetFile : dataSetFiles) { readDataSetFile(xmlReader, dataSetFile); } return dataSetContentHandler.getMultiSchemaDataSet(); }
From source file:org.unitils.dbunit.util.MultiSchemaXmlDataSetReader.java
/** * Parses the datasets from the given files. * Each schema is given its own dataset and each row is given its own table. * * @param dataSetFiles The dataset files, not null * @return The read data set, not null//w w w. j a v a 2 s. com */ public MultiSchemaDataSet readDataSetXml(File... dataSetFiles) { try { DataSetContentHandler dataSetContentHandler = new DataSetContentHandler(defaultSchemaName); XMLReader xmlReader = createXMLReader(); xmlReader.setContentHandler(dataSetContentHandler); xmlReader.setErrorHandler(dataSetContentHandler); for (File dataSetFile : dataSetFiles) { InputStream dataSetInputStream = null; try { dataSetInputStream = new FileInputStream(dataSetFile); xmlReader.parse(new InputSource(dataSetInputStream)); } finally { closeQuietly(dataSetInputStream); } } return dataSetContentHandler.getMultiSchemaDataSet(); } catch (Exception e) { throw new UnitilsException("Unable to parse data set xml.", e); } }
From source file:org.webcurator.core.profiles.HeritrixProfile.java
/** * Reconstruct a profile from an XML string. * @param str The XML string to create the profile from. * @return The object representation of the profile string. *///from w w w . ja v a 2 s. c o m public static HeritrixProfile fromString(String str) { try { XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); StringReader reader = new StringReader(str); // Create a settings handler. The file is a dummy file simply to allow // us to construct the object. XMLSettingsHandler settingsHandler = new XMLSettingsHandler(new File("dummy_file")); parser.setContentHandler(new CrawlSettingsSAXHandler(settingsHandler.getSettings(null))); InputSource source = new InputSource(reader); parser.parse(source); HeritrixProfile profile = new HeritrixProfile(settingsHandler, null); return profile; } catch (SAXException ex) { throw new WCTRuntimeException(ex); } catch (ParserConfigurationException pcex) { throw new WCTRuntimeException(pcex); } catch (IOException e) { throw new WCTRuntimeException(e); } catch (InvalidAttributeValueException e) { throw new WCTRuntimeException(e); } }
From source file:org.wyona.yanel.impl.resources.TestingControlResource.java
/** * //ww w.ja va2 s . c o m */ public View getView(String viewId) { if (request.getHeader("User-Agent").indexOf("rv:1.7") < 0) { ajaxBrowser = true; } try { setLocations(); } catch (Exception e) { // sb.append("<p>Could not get the Locations: " + e + "</p>"); log.error(e.getMessage(), e); } View view = new View(); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); try { org.wyona.yarep.core.Repository repo = getRealm().getRepository(); if (viewId != null && viewId.equals("source")) { view.setInputStream(new java.io.StringBufferInputStream(getScreen())); view.setMimeType("application/xml"); return view; } String[] xsltPath = getXSLTPath(getPath()); if (xsltPath != null) { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length]; for (int i = 0; i < xsltPath.length; i++) { xsltHandlers[i] = tf .newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]).getInputStream())); xsltHandlers[i].getTransformer().setParameter("yanel.path.name", org.wyona.commons.io.PathUtil.getName(getPath())); xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath()); xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage()); } // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage()); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); ResourceResolver resolver = new ResourceResolver(this); xIncludeTransformer.setResolver(resolver); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): xmlReader.setContentHandler(xsltHandlers[0]); for (int i = 0; i < xsltHandlers.length - 1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i + 1])); } xsltHandlers[xsltHandlers.length - 1].setResult(new SAXResult(xIncludeTransformer)); xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen()))); // write result into view: view.setInputStream(new ByteArrayInputStream(baos.toByteArray())); return view; } log.debug("Mime-Type: " + mimeType); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } catch (Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); } view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; }
From source file:org.xwiki.extension.xar.internal.handler.packager.DefaultPackager.java
public void parseDocument(InputStream in, ContentHandler documentHandler) throws ParserConfigurationException, SAXException, IOException, NotADocumentException { SAXParser saxParser = this.parserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); RootHandler handler = new RootHandler(this.componentManager); handler.setHandler("xwikidoc", documentHandler); xmlReader.setContentHandler(handler); try {//from w ww .j a va 2s . c o m xmlReader.parse(new InputSource(new CloseShieldInputStream(in))); } catch (UnknownRootElement e) { throw new NotADocumentException("Failed to parse stream", e); } }