List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:org.roda.core.common.validation.ValidationUtils.java
public static ValidationReport isXMLValid(ContentPayload xmlPayload) { ValidationReport ret = new ValidationReport(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);//from w w w .j av a 2 s . c om factory.setNamespaceAware(true); RodaErrorHandler errorHandler = new RodaErrorHandler(); try (Reader reader = new InputStreamReader(new BOMInputStream(xmlPayload.createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource inputSource = new InputSource(reader); xmlReader.setErrorHandler(errorHandler); xmlReader.parse(inputSource); ret.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { ret.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (IOException e) { ret.setValid(false); ret.setMessage(e.getMessage()); } return ret; }
From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java
/** * Scans the classloader for files named META-INF/orm.xml and consolidates * them./* w w w .j ava 2s . c o m*/ * * @return A consolidated String representing all orm.xml files found. * @throws IOException * @throws SAXException */ private String scanOrmXml() throws TransformerConfigurationException, IOException, SAXException { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); // SAX2.0 ContentHandler SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = tf.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(result); JpaOrmAccumulator acc = new JpaOrmAccumulator(handler); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(acc); for (final URL url : findXMLs(ORM_XML)) { reader.parse(new InputSource(url.openStream())); } String writerOut = writer.toString(); String out = XML_HEADER + ENTITY_MAPPINGS_START + writerOut.substring(writerOut.indexOf("<entity ")) + ENTITY_MAPPINGS_END; return out; }
From source file:org.sakaiproject.search.component.service.impl.SearchListResponseImpl.java
public SearchListResponseImpl(String response, Query query, int start, int end, Analyzer analyzer, SearchItemFilter filter, SearchIndexBuilder searchIndexBuilder, SearchService searchService) throws SAXException, IOException { this.query = query; this.start = start; this.end = end; this.analyzer = analyzer; this.filter = filter; this.searchIndexBuilder = searchIndexBuilder; this.searchService = searchService; if (log.isDebugEnabled()) { log.debug("search response: [" + response + "]"); }/*from w w w . j a v a 2 s.co m*/ XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(this); InputSource is = new InputSource(new StringReader(response)); xr.parse(is); if (errorMessage != null) { log.error("Failed to perform remote request, remote exception was: \n" + errorMessage); throw new IOException("Failed to perform remote request "); } }
From source file:org.sakaiproject.warehouse.util.db.DbLoader.java
protected void readProperties(XMLReader parser, InputStream properties) throws SAXException, IOException { propertiesHandler = new PropertiesHandler(); parser.setContentHandler(propertiesHandler); parser.setErrorHandler(propertiesHandler); parser.parse(new InputSource(properties)); }
From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl2.java
private void parseAndValidate(InputStream input, Schema schema) throws XmlParseException, IOException { ValidatorHandler vHandler = schema.newValidatorHandler(); vHandler.setContentHandler(this); vHandler.setErrorHandler(this); InputSource is = new InputSource(new InputStreamReader(input, "UTF-8")); is.setEncoding("UTF-8"); try {/*from w ww . j av a2 s .c o m*/ XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(vHandler); parser.setErrorHandler(this); vHandler.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); parser.setFeature("http://apache.org/xml/features/validation/id-idref-checking", false); parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.parse(is); } catch (SAXException e) { throw new XmlParseException(e.getMessage(), e); } }
From source file:org.soaplab.services.metadata.MetadataAccessorXML.java
/************************************************************************** * parsing an XML input//from w w w.jav a 2 s . c o m **************************************************************************/ private synchronized void load(String xmlFilename) throws SoaplabException { InputSource xmlSource = new InputSource(xmlFilename); try { // Create the parser and register handlers XMLReader parser = XMLUtils2.makeXMLParser(this); // Parse it! parser.parse(xmlSource); } catch (GException e) { throw new SoaplabException("Error in creating XML parser " + e.getMessage()); } catch (SAXException e) { throw new SoaplabException("Error in the XML input.\n" + XMLUtils2.getFormattedError(e)); } catch (IOException e) { throw new SoaplabException("Error by reading XML input: " + e.getMessage()); } catch (Error e) { throw new SoaplabException("Serious or unexpected error!\n" + e.toString(), e); } }
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 w w . ja va2 s . 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/>/* w ww. jav a2 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;// ww w. j av a2s.c o m 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;//from w w w.j a 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; }