List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java
@Override public XMLReader createValidatingParser(IPipeLineSession session, ValidationContext context) throws XmlValidatorException, PipeRunException { SAXParser parser;//w w w . j a v a2 s . c o m try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(false); parserFactory.setNamespaceAware(true); parserFactory.setFeature(PARSING_FEATURE_SECURE, true); //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_GENERAL_ENTITIES, false); //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_PARAMETER_ENTITIES, false); //parserFactory.setFeature(PARSING_FEATURE_DISALLOW_INLINE_DOCTYPE, true); Schema schema = getSchemaObject(context.getSchemasId(), schemasProvider.getSchemas(session)); parserFactory.setSchema(schema); parser = parserFactory.newSAXParser(); return parser.getXMLReader(); } catch (ParserConfigurationException e) { throw new XmlValidatorException(logPrefix + "cannot configure parser", e); } catch (ConfigurationException e) { throw new XmlValidatorException(logPrefix + "cannot configure parser", e); } catch (SAXException e) { throw new XmlValidatorException(logPrefix + "cannot create parser", e); } }
From source file:org.apache.fop.accessibility.AccessibilityPreprocessor.java
/** {@inheritDoc} */ public void endDocument() throws SAXException { super.endDocument(); // do the second transform to struct try {//from w w w . j a va 2s .c o m //TODO this must be optimized, no buffering (ex. SAX-based tee-proxy) byte[] enrichedFO = enrichedFOBuffer.toByteArray(); Source src = new StreamSource(new ByteArrayInputStream(enrichedFO)); DOMResult res = new DOMResult(); reduceFOTree.transform(src, res); StructureTree structureTree = new StructureTree(); NodeList pageSequences = res.getNode().getFirstChild().getChildNodes(); for (int i = 0; i < pageSequences.getLength(); i++) { structureTree.addPageSequenceStructure(pageSequences.item(i).getChildNodes()); } userAgent.setStructureTree(structureTree); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); saxParserFactory.setValidating(false); SAXParser saxParser = saxParserFactory.newSAXParser(); InputStream in = new ByteArrayInputStream(enrichedFO); saxParser.parse(in, fopHandler); } catch (Exception e) { throw new SAXException(e); } }
From source file:org.apache.fop.fotreetest.FOTreeTestCase.java
/** * Runs a test./*from www .j ava 2s . c o m*/ * @throws Exception if a test or FOP itself fails */ @Test public void runTest() throws Exception { try { ResultCollector collector = ResultCollector.getInstance(); collector.reset(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); SAXParser parser = spf.newSAXParser(); XMLReader reader = parser.getXMLReader(); // Resetting values modified by processing instructions fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary( FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE); fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION); FOUserAgent ua = fopFactory.newFOUserAgent(); ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString()); ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua)); ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName())); // Used to set values in the user agent through processing instructions reader = new PIListener(reader, ua); Fop fop = fopFactory.newFop(ua); reader.setContentHandler(fop.getDefaultHandler()); reader.setDTDHandler(fop.getDefaultHandler()); reader.setErrorHandler(fop.getDefaultHandler()); reader.setEntityResolver(fop.getDefaultHandler()); try { reader.parse(testFile.toURI().toURL().toExternalForm()); } catch (Exception e) { collector.notifyError(e.getLocalizedMessage()); throw e; } List<String> results = collector.getResults(); if (results.size() > 0) { for (int i = 0; i < results.size(); i++) { System.out.println((String) results.get(i)); } throw new IllegalStateException((String) results.get(0)); } } catch (Exception e) { org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName()); throw e; } }
From source file:org.apache.geode.internal.cache.xmlcache.CacheXmlParser.java
/** * Parses XML data and from it creates an instance of <code>CacheXmlParser</code> that can be used * to {@link #create}the {@link Cache}, etc. * * @param is the <code>InputStream</code> of XML to be parsed * * @return a <code>CacheXmlParser</code>, typically used to create a cache from the parsed XML * * @throws CacheXmlException Something went wrong while parsing the XML * * @since GemFire 4.0// w w w. j a va 2s . com * */ public static CacheXmlParser parse(InputStream is) { /** * The API doc http://java.sun.com/javase/6/docs/api/org/xml/sax/InputSource.html for the SAX * InputSource says: "... standard processing of both byte and character streams is to close * them on as part of end-of-parse cleanup, so applications should not attempt to re-use such * streams after they have been handed to a parser." * * In order to block the parser from closing the stream, we wrap the InputStream in a filter, * i.e., UnclosableInputStream, whose close() function does nothing. * */ class UnclosableInputStream extends BufferedInputStream { public UnclosableInputStream(InputStream stream) { super(stream); } @Override public void close() { } } CacheXmlParser handler = new CacheXmlParser(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, true); factory.setValidating(true); factory.setNamespaceAware(true); UnclosableInputStream bis = new UnclosableInputStream(is); try { SAXParser parser = factory.newSAXParser(); // Parser always reads one buffer plus a little extra worth before // determining that the DTD is there. Setting mark twice the parser // buffer size. bis.mark((Integer) parser.getProperty(BUFFER_SIZE) * 2); parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI); parser.parse(bis, new DefaultHandlerDelegate(handler)); } catch (CacheXmlException e) { if (null != e.getCause() && e.getCause().getMessage().contains(DISALLOW_DOCTYPE_DECL_FEATURE)) { // Not schema based document, try dtd. bis.reset(); factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, false); SAXParser parser = factory.newSAXParser(); parser.parse(bis, new DefaultHandlerDelegate(handler)); } else { throw e; } } return handler; } catch (Exception ex) { if (ex instanceof CacheXmlException) { while (true /* ex instanceof CacheXmlException */) { Throwable cause = ex.getCause(); if (!(cause instanceof CacheXmlException)) { break; } else { ex = (CacheXmlException) cause; } } throw (CacheXmlException) ex; } else if (ex instanceof SAXException) { // Silly JDK 1.4.2 XML parser wraps RunTime exceptions in a // SAXException. Pshaw! SAXException sax = (SAXException) ex; Exception cause = sax.getException(); if (cause instanceof CacheXmlException) { while (true /* cause instanceof CacheXmlException */) { Throwable cause2 = cause.getCause(); if (!(cause2 instanceof CacheXmlException)) { break; } else { cause = (CacheXmlException) cause2; } } throw (CacheXmlException) cause; } } throw new CacheXmlException(LocalizedStrings.CacheXmlParser_WHILE_PARSING_XML.toLocalizedString(), ex); } }
From source file:org.apache.hadoop.hbase.rest.TestTableScan.java
/** * An example to scan using listener in unmarshaller for XML. * @throws Exception the exception/*from w w w . j a v a2 s .c o m*/ */ @Test public void testScanUsingListenerUnmarshallerXML() throws Exception { StringBuilder builder = new StringBuilder(); builder.append("/*"); builder.append("?"); builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1); builder.append("&"); builder.append(Constants.SCAN_LIMIT + "=10"); Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_XML); assertEquals(200, response.getCode()); assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type")); JAXBContext context = JAXBContext.newInstance(ClientSideCellSetModel.class, RowModel.class, CellModel.class); Unmarshaller unmarshaller = context.createUnmarshaller(); final ClientSideCellSetModel.Listener listener = new ClientSideCellSetModel.Listener() { @Override public void handleRowModel(ClientSideCellSetModel helper, RowModel row) { assertTrue(row.getKey() != null); assertTrue(row.getCells().size() > 0); } }; // install the callback on all ClientSideCellSetModel instances unmarshaller.setListener(new Unmarshaller.Listener() { public void beforeUnmarshal(Object target, Object parent) { if (target instanceof ClientSideCellSetModel) { ((ClientSideCellSetModel) target).setCellSetModelListener(listener); } } public void afterUnmarshal(Object target, Object parent) { if (target instanceof ClientSideCellSetModel) { ((ClientSideCellSetModel) target).setCellSetModelListener(null); } } }); // create a new XML parser SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); assertFalse(ClientSideCellSetModel.listenerInvoked); reader.parse(new InputSource(response.getStream())); assertTrue(ClientSideCellSetModel.listenerInvoked); }
From source file:org.apache.jackrabbit.jcr2spi.SessionImpl.java
/** * @see javax.jcr.Session#importXML(String, java.io.InputStream, int) */// w w w.j a v a2 s . co m @Override public void importXML(String parentAbsPath, InputStream in, int uuidBehavior) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, VersionException, InvalidSerializedDataException, LockException, RepositoryException { // NOTE: checks are performed by 'getImportContentHandler' ImportHandler handler = (ImportHandler) getImportContentHandler(parentAbsPath, uuidBehavior); try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", false); SAXParser parser = factory.newSAXParser(); parser.parse(new InputSource(in), handler); } catch (SAXException se) { // check for wrapped repository exception Exception e = se.getException(); if (e != null && e instanceof RepositoryException) { throw (RepositoryException) e; } else { String msg = "failed to parse XML stream"; log.debug(msg); throw new InvalidSerializedDataException(msg, se); } } catch (ParserConfigurationException e) { throw new RepositoryException("SAX parser configuration error", e); } finally { in.close(); // JCR-2903 } }
From source file:org.apache.myfaces.custom.skin.config.ConfigParser.java
/** * */// w ww.j a v a2 s . c o m static public RequestContextBean parseConfigFile(ExternalContext externalContext) { RequestContextBean bean = new RequestContextBean(); InputStream in = externalContext.getResourceAsStream(_SKINS_CONFIG_FILE); if (in == null) { in = externalContext.getResourceAsStream(_TRINIDAD_CONFIG_FILE); } if (in != null) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); Digester digester = new Digester(factory.newSAXParser()); digester.setValidating(false); digester.setNamespaceAware(true); digester.setUseContextClassLoader(true); RequestContextBean.addXmlRules(digester); InputSource input = new InputSource(); input.setByteStream(in); input.setPublicId(_SKINS_CONFIG_FILE); digester.parse(input); bean = (RequestContextBean) digester.getRoot(); } catch (IOException ioe) { _LOG.warning(ioe); } catch (ParserConfigurationException pce) { _LOG.warning(pce); } catch (SAXException saxe) { _LOG.warning(saxe); } finally { try { in.close(); } catch (IOException ioe) { // Ignore ; } } } return bean; }
From source file:org.apache.myfaces.test.AbstractClassElementTestCase.java
protected void setUp() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);//from w ww. j av a 2 s. c om factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); ClassElementHandler handler = new DelegateEntityResolver(); Iterator iterator = resource.iterator(); while (iterator.hasNext()) { String resourceName = (String) iterator.next(); InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName); if (is == null) is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); if (is == null) throw new Exception("Could not locate resource :" + resourceName); parser.parse(is, handler); } className.addAll(handler.getClassName()); }
From source file:org.apache.myfaces.trinidadbuild.plugin.faces.AbstractFacesMojo.java
protected URL[] readIndex(MavenProject project) throws MojoExecutionException { try {//from w ww . j a v a2s . co m // 1. read master faces-config.xml resources List masters = getMasterConfigs(project); if (masters.isEmpty()) { getLog().warn("Master faces-config.xml not found"); return new URL[0]; } else { List entries = new LinkedList(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); // requires JAXP 1.3, in JavaSE 5.0 // spf.setXIncludeAware(false); for (Iterator<URL> i = masters.iterator(); i.hasNext();) { URL url = i.next(); Digester digester = new Digester(spf.newSAXParser()); digester.setNamespaceAware(true); // XInclude digester.setRuleNamespaceURI(XIncludeFilter.XINCLUDE_NAMESPACE); digester.addCallMethod("faces-config/include", "add", 1); digester.addFactoryCreate("faces-config/include", URLCreationFactory.class); digester.addCallParam("faces-config/include", 0, 0); digester.push(url); digester.push(entries); digester.parse(url.openStream()); } return (URL[]) entries.toArray(new URL[0]); } } catch (ParserConfigurationException e) { throw new MojoExecutionException("Failed to parse master config", e); } catch (SAXException e) { throw new MojoExecutionException("Failed to parse master config", e); } catch (IOException e) { throw new MojoExecutionException("Failed to parse master config", e); } }
From source file:org.apache.myfaces.trinidadbuild.plugin.faces.parse.FacesConfigParser.java
static protected Digester createEmptyDigester() throws ParserConfigurationException, SAXException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); // requires JAXP 1.3, in JavaSE 5.0 // spf.setXIncludeAware(true); Digester digester = new Digester(spf.newSAXParser()); digester.setNamespaceAware(true);/*from w w w. j ava2s .c o m*/ return digester; }