List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:org.apache.flex.compiler.internal.config.FileConfigurator.java
/** * Load configuration XML file into a {@link ConfigurationBuffer} object. * //from ww w.j a va 2 s.c o m * @param buffer result {@link ConfigurationBuffer} object. * @param fileSpec configuration XML file. * @param context path context used for resolving relative paths in the * configuration options. * @param rootElement expected root element of the XML DOM tree. * @param ignoreUnknownItems if false, unknown option will cause exception. * @throws ConfigurationException error. */ public static void load(final ConfigurationBuffer buffer, final IFileSpecification fileSpec, final String context, final String rootElement, boolean ignoreUnknownItems) throws ConfigurationException { final String path = fileSpec.getPath(); final Handler h = new Handler(buffer, path, context, rootElement, ignoreUnknownItems); final SAXParserFactory factory = SAXParserFactory.newInstance(); Reader reader = null; try { reader = fileSpec.createReader(); final SAXParser parser = factory.newSAXParser(); final InputSource source = new InputSource(reader); parser.parse(source, h); } catch (SAXConfigurationException e) { throw e.innerException; } catch (SAXParseException e) { throw new ConfigurationException.OtherThrowable(e, null, path, e.getLineNumber()); } catch (Exception e) { throw new ConfigurationException.OtherThrowable(e, null, path, -1); } finally { IOUtils.closeQuietly(reader); } }
From source file:org.apache.fop.accessibility.AccessibilityPreprocessor.java
/** {@inheritDoc} */ public void endDocument() throws SAXException { super.endDocument(); // do the second transform to struct try {/*w w w . j a v a2 s .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.cli.InputHandler.java
private XMLReader getXMLReader() throws ParserConfigurationException, SAXException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://apache.org/xml/features/xinclude", true); XMLReader xr = spf.newSAXParser().getXMLReader(); return xr;// w w w.ja va2 s .c o m }
From source file:org.apache.fop.complexscripts.fonts.ttx.TTXFile.java
public void parse(File f) { assert f != null; try {/* w w w .j a v a 2s. com*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); sp.parse(f, new Handler()); } catch (FactoryConfigurationError e) { throw new RuntimeException(e.getMessage()); } catch (ParserConfigurationException e) { throw new RuntimeException(e.getMessage()); } catch (SAXException e) { throw new RuntimeException(e.getMessage()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } }
From source file:org.apache.fop.fo.extensions.svg.SVGElementMapping.java
/** * Returns the fully qualified classname of an XML parser for * Batik classes that apparently need it (error messages, perhaps) * @return an XML parser classname//from w ww . j a va 2s. c o m */ private String getAParserClassName() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); return factory.newSAXParser().getXMLReader().getClass().getName(); } catch (Exception e) { return null; } }
From source file:org.apache.fop.fotreetest.FOTreeTestCase.java
/** * Runs a test./*from ww w . j a va 2s. co 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.fop.image.loader.batik.PreloaderSVG.java
/** * Returns the fully qualified classname of an XML parser for * Batik classes that apparently need it (error messages, perhaps) * @return an XML parser classname/*from www . j a v a2s . c o m*/ */ public static String getParserName() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); return factory.newSAXParser().getXMLReader().getClass().getName(); } catch (Exception e) { return null; } }
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/*from w ww . j a v a 2s. c o m*/ * */ 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/* ww w. jav a2s. 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.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewerForAcl.java
@Test public void testPBImageXmlWriterForAcl() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintStream o = new PrintStream(output); PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), o); v.visit(new RandomAccessFile(originalFsimage, "r")); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); final String xml = output.toString(); parser.parse(new InputSource(new StringReader(xml)), new DefaultHandler()); }