List of usage examples for javax.xml.transform.sax SAXSource getXMLReader
public XMLReader getXMLReader()
From source file:net.sf.joost.trax.TransformerFactoryImpl.java
/** * Creates a new Templates for Transformations. * @param source The <code>Source</code> of the stylesheet. * @return A <code>Templates</code> object or <code>null</code> when an error * occured (no user defined ErrorListener) * @throws TransformerConfigurationException *///from ww w.j a v a 2 s.c om public Templates newTemplates(Source source) throws TransformerConfigurationException { synchronized (reentryGuard) { if (DEBUG) { if (log.isDebugEnabled()) log.debug("get a Templates-instance from Source " + source.getSystemId()); } try { SAXSource saxSource = TrAXHelper.getSAXSource(source, errorListener); Templates template = new TemplatesImpl(saxSource.getXMLReader(), saxSource.getInputSource(), this); return template; } catch (TransformerException tE) { defaultErrorListener.fatalError(tE); return null; } } }
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult, * DOMResult and StreamResult/*from w w w .j a v a 2s .co m*/ * * @param xmlSource A <code>Source</code> * @param result A <code>Result</code> * @throws TransformerException */ public void transform(Source xmlSource, Result result) throws TransformerException { StxEmitter out = null; SAXSource saxSource = null; // should be synchronized synchronized (reentryGuard) { if (DEBUG) log.debug("perform transformation from " + "xml-source(SAXSource, DOMSource, StreamSource) " + "to SAXResult, DOMResult or StreamResult"); try { // init StxEmitter out = TrAXHelper.initStxEmitter(result, processor, null); out.setSystemId(result.getSystemId()); this.processor.setContentHandler(out); this.processor.setLexicalHandler(out); // register ErrorListener if (this.errorListener != null) { this.processor.setErrorListener(errorListener); } // construct from source a SAXSource saxSource = TrAXHelper.getSAXSource(xmlSource, errorListener); InputSource isource = saxSource.getInputSource(); if (isource != null) { if (DEBUG) log.debug("perform transformation"); if (saxSource.getXMLReader() != null) { // should not be an DOMSource if (xmlSource instanceof SAXSource) { XMLReader xmlReader = ((SAXSource) xmlSource).getXMLReader(); /** * URIs for Identifying Feature Flags and Properties : * There is no fixed set of features or properties * available for SAX2, except for two features that all XML * parsers must support. Implementors are free to define * new features and properties as needed, using URIs to * identify them. * * All XML readers are required to recognize the * "http://xml.org/sax/features/namespaces" and the * "http://xml.org/sax/features/namespace-prefixes" * features (at least to get the feature values, if not set * them) and to support a true value for the namespaces * property and a false value for the namespace-prefixes * property. These requirements ensure that all SAX2 XML * readers can provide the minimal required Namespace * support for higher-level specs such as RDF, XSL, XML * Schemas, and XLink. XML readers are not required to * recognize or support any other features or any * properties. * * For the complete list of standard SAX2 features and * properties, see the {@link org.xml.sax} Package * Description. */ if (xmlReader != null) { try { // set the required // "http://xml.org/sax/features/namespaces" Feature xmlReader.setFeature(FEAT_NS, true); // set the required // "http://xml.org/sax/features/namespace-prefixes" // Feature xmlReader.setFeature(FEAT_NSPREFIX, false); // maybe there would be other features } catch (SAXException sE) { getErrorListener().warning(new TransformerException(sE.getMessage(), sE)); } } } // set the the SAXSource as the parent of the STX-Processor this.processor.setParent(saxSource.getXMLReader()); } // perform transformation this.processor.parse(isource); } else { TransformerException tE = new TransformerException( "InputSource is null - could not perform transformation"); getErrorListener().fatalError(tE); } // perform result performResults(result, out); } catch (SAXException ex) { TransformerException tE; Exception emb = ex.getException(); if (emb instanceof TransformerException) { tE = (TransformerException) emb; } else { tE = new TransformerException(ex.getMessage(), ex); } getErrorListener().fatalError(tE); } catch (IOException ex) { // will this ever happen? getErrorListener().fatalError(new TransformerException(ex.getMessage(), ex)); } } }
From source file:nl.nn.adapterframework.util.XmlUtils.java
static public boolean isWellFormed(String input, String root) { Set<List<String>> rootValidations = null; if (StringUtils.isNotEmpty(root)) { List<String> path = new ArrayList<String>(); path.add(root);/*from w w w . j a va 2 s. co m*/ rootValidations = new HashSet<List<String>>(); rootValidations.add(path); } XmlValidatorContentHandler xmlHandler = new XmlValidatorContentHandler(null, rootValidations, null, true); XmlValidatorErrorHandler xmlValidatorErrorHandler = new XmlValidatorErrorHandler(xmlHandler, "Is not well formed"); xmlHandler.setXmlValidatorErrorHandler(xmlValidatorErrorHandler); try { SAXSource saxSource = stringToSAXSource(input, true, false); XMLReader xmlReader = saxSource.getXMLReader(); xmlReader.setContentHandler(xmlHandler); // Prevent message in System.err: [Fatal Error] :-1:-1: Premature end of file. xmlReader.setErrorHandler(xmlValidatorErrorHandler); xmlReader.parse(saxSource.getInputSource()); } catch (Exception e) { return false; } return true; }
From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java
public Schema newSchema(Source[] schemas) throws SAXException { // this will let the loader store parsed Grammars into the pool. XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension(); fXMLGrammarPoolWrapper.setGrammarPool(pool); XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length]; InputStream inputStream;//from w w w .j a v a2 s . co m Reader reader; for (int i = 0; i < schemas.length; ++i) { Source source = schemas[i]; if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; String publicId = streamSource.getPublicId(); String systemId = streamSource.getSystemId(); inputStream = streamSource.getInputStream(); reader = streamSource.getReader(); XMLInputSource xmlInputSource = new XMLInputSource(publicId, systemId, null); xmlInputSource.setByteStream(inputStream); xmlInputSource.setCharacterStream(reader); xmlInputSources[i] = xmlInputSource; } else if (source instanceof SAXSource) { SAXSource saxSource = (SAXSource) source; InputSource inputSource = saxSource.getInputSource(); if (inputSource == null) { throw new SAXException(JAXPValidationMessageFormatter .formatMessage(fXMLSchemaLoader.getLocale(), "SAXSourceNullInputSource", null)); } xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource); } else if (source instanceof DOMSource) { DOMSource domSource = (DOMSource) source; Node node = domSource.getNode(); String systemID = domSource.getSystemId(); xmlInputSources[i] = new DOMInputSource(node, systemID); } // else if (source instanceof StAXSource) { // StAXSource staxSource = (StAXSource) source; // XMLEventReader eventReader = staxSource.getXMLEventReader(); // if (eventReader != null) { // xmlInputSources[i] = new StAXInputSource(eventReader); // } // else { // xmlInputSources[i] = new StAXInputSource(staxSource.getXMLStreamReader()); // } // } else if (source == null) { throw new NullPointerException(JAXPValidationMessageFormatter .formatMessage(fXMLSchemaLoader.getLocale(), "SchemaSourceArrayMemberNull", null)); } else { throw new IllegalArgumentException( JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(), "SchemaFactorySourceUnrecognized", new Object[] { source.getClass().getName() })); } } try { fXMLSchemaLoader.loadGrammar(xmlInputSources); } catch (XNIException e) { // this should have been reported to users already. throw Util.toSAXException(e); } catch (IOException e) { // this hasn't been reported, so do so now. SAXParseException se = new SAXParseException(e.getMessage(), null, e); if (fErrorHandler != null) { fErrorHandler.error(se); } throw se; // and we must throw it. } // Clear reference to grammar pool. fXMLGrammarPoolWrapper.setGrammarPool(null); // Select Schema implementation based on grammar count. final int grammarCount = pool.getGrammarCount(); AbstractXMLSchema schema = null; if (fUseGrammarPoolOnly) { throw new NotImplementedException("fUseGrammarPoolOnly"); // if (grammarCount > 1) { // schema = new XMLSchemaHack(new ReadOnlyGrammarPool(pool)); // } // else if (grammarCount == 1) { // Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA); // schema = new XMLSchemaHack(grammars[0]); // } // else { // schema = new XMLSchemaHack(); // } } else { schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false); } propagateFeatures(schema); return schema; }
From source file:org.betaconceptframework.astroboa.engine.jcr.io.Deserializer.java
public <T> T deserializeContent(InputStream source, boolean jsonSource, Class<T> classWhoseContentIsImported, ImportConfiguration configuration) { if (configuration != null) { persistMode = configuration.getPersistMode(); version = configuration.isVersion(); updateLastModificationDate = configuration.isUpdateLastModificationTime(); }/*from w w w.ja va2 s.com*/ if (persistMode == null) { if (classWhoseContentIsImported == Repository.class || List.class.isAssignableFrom(classWhoseContentIsImported)) { persistMode = PersistMode.PERSIST_ENTITY_TREE; } else { persistMode = PersistMode.DO_NOT_PERSIST; } } context = new Context(cmsRepositoryEntityUtils, cmsQueryHandler, session, configuration); XMLStreamReader xmlStreamReader = null; SAXSource saxSource = null; try { Object entity = null; long start = System.currentTimeMillis(); if (jsonSource) { xmlStreamReader = CmsEntityDeserialization.Context.createJSONReader(source, true, classWhoseContentIsImported); JsonImportContentHandler<T> handler = new JsonImportContentHandler(classWhoseContentIsImported, this); XMLStreamReaderToContentHandler xmlStreamReaderToContentHandler = new XMLStreamReaderToContentHandler( xmlStreamReader, handler, false, false); xmlStreamReaderToContentHandler.bridge(); entity = handler.getResult(); logger.debug(" Unmarshal json to {} took {}", classWhoseContentIsImported.getSimpleName(), DurationFormatUtils.formatDuration(System.currentTimeMillis() - start, "HH:mm:ss.SSSSSS")); } else { saxSource = CmsEntityDeserialization.Context.createSAXSource(source, repositoryEntityResolver, false); //we explicitly disable validation because partial saves are allowed ImportContentHandler<T> handler = new ImportContentHandler(classWhoseContentIsImported, this); saxSource.getXMLReader().setContentHandler(handler); saxSource.getXMLReader().parse(saxSource.getInputSource()); entity = handler.getImportResult(); logger.debug("Unmarshal xml to {} took {}", classWhoseContentIsImported.getSimpleName(), DurationFormatUtils.formatDuration(System.currentTimeMillis() - start, "HH:mm:ss.SSSSSS")); } //If entity is not of type T then a class cast exception is thrown. if (entity instanceof CmsRepositoryEntity) { entity = save((CmsRepositoryEntity) entity); } return (T) entity; } catch (CmsException e) { logger.error("", e); throw e; } catch (Exception e) { logger.error("", e); throw new CmsException(e.getMessage()); } finally { if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { //Ignore exception } } if (saxSource != null && saxSource.getInputSource() != null) { IOUtils.closeQuietly(saxSource.getInputSource().getByteStream()); IOUtils.closeQuietly(saxSource.getInputSource().getCharacterStream()); } if (context != null) { context.dispose(); context = null; } } }
From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java
@SuppressWarnings("deprecation") // on JDK 9 private Source processSource(Source source) { if (StaxUtils.isStaxSource(source) || source instanceof DOMSource) { return source; }/*from w w w. jav a 2s . com*/ XMLReader xmlReader = null; InputSource inputSource = null; if (source instanceof SAXSource) { SAXSource saxSource = (SAXSource) source; xmlReader = saxSource.getXMLReader(); inputSource = saxSource.getInputSource(); } else if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; if (streamSource.getInputStream() != null) { inputSource = new InputSource(streamSource.getInputStream()); } else if (streamSource.getReader() != null) { inputSource = new InputSource(streamSource.getReader()); } else { inputSource = new InputSource(streamSource.getSystemId()); } } try { if (xmlReader == null) { xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); } xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); String name = "http://xml.org/sax/features/external-general-entities"; xmlReader.setFeature(name, isProcessExternalEntities()); if (!isProcessExternalEntities()) { xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } return new SAXSource(xmlReader, inputSource); } catch (SAXException ex) { logger.warn("Processing of external entities could not be disabled", ex); return source; } }
From source file:org.springframework.oxm.support.AbstractMarshaller.java
/** * Template method for handling {@code SAXSource}s. * <p>This implementation delegates to {@code unmarshalSaxReader}. * @param saxSource the {@code SAXSource} * @return the object graph/*from w ww. j a v a2s . c om*/ * @throws XmlMappingException if the given source cannot be mapped to an object * @throws IOException if an I/O Exception occurs * @see #unmarshalSaxReader(org.xml.sax.XMLReader, org.xml.sax.InputSource) */ protected Object unmarshalSaxSource(SAXSource saxSource) throws XmlMappingException, IOException { if (saxSource.getXMLReader() == null) { try { saxSource.setXMLReader(createXmlReader()); } catch (SAXException ex) { throw new UnmarshallingFailureException("Could not create XMLReader for SAXSource", ex); } } if (saxSource.getInputSource() == null) { saxSource.setInputSource(new InputSource()); } try { return unmarshalSaxReader(saxSource.getXMLReader(), saxSource.getInputSource()); } catch (NullPointerException ex) { if (!isSupportDtd()) { throw new UnmarshallingFailureException( "NPE while unmarshalling. " + "This can happen on JDK 1.6 due to the presence of DTD " + "declarations, which are disabled."); } throw ex; } }