@Test public void test() throws SAXException, ParserConfigurationException, IOException { Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(new StringReader(xmlSchema))); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); saxParserFactory.setSchema(schema); // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", // true); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new MyContentHandler()); // InputStream input = // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml"); InputStream input = getClass().getResourceAsStream("Bug6946312.xml"); System.out.println("Parse InputStream:"); xmlReader.parse(new InputSource(input)); if (!charEvent) { Assert.fail("missing character event"); } }
private static SAXParser getSAXParser( boolean validating, JspDocumentParser jspDocParser) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // Preserve xmlns attributes factory.setFeature( "http://xml.org/sax/features/namespace-prefixes", true); factory.setValidating(validating); //factory.setFeature( // "http://xml.org/sax/features/validation", // validating); // Configure the parser SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser); xmlReader.setErrorHandler(jspDocParser); return saxParser; }
/** * Configure schema validation as recommended by the JAXP 1.2 spec. * The <code>properties</code> object may contains information about * the schema local and language. * @param properties parser optional info */ private static void configureOldXerces(SAXParser parser, Properties properties) throws ParserConfigurationException, SAXNotSupportedException { String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } }
/** * Create a <code>SAXParser</code> configured to support XML Schema and DTD * @param properties parser specific properties/features * @return an XML Schema/DTD enabled <code>SAXParser</code> */ public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotRecognizedException{ SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); SAXParser parser = factory.newSAXParser(); String schemaLocation = (String)properties.get("schemaLocation"); String schemaLanguage = (String)properties.get("schemaLanguage"); try{ if (schemaLocation != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation); } } catch (SAXNotRecognizedException e){ log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported."); } return parser; }
/** * Test default handler that transverses XML and print all visited node. * * @throws Exception If any errors occur. */ @Test public void testDefaultHandler() throws Exception { String outputFile = USER_DIR + "DefaultHandler.out"; String goldFile = GOLDEN_DIR + "DefaultHandlerGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxparser = spf.newSAXParser(); MyDefaultHandler handler = new MyDefaultHandler(outputFile); File file = new File(xmlFile); String Absolutepath = file.getAbsolutePath(); String newAbsolutePath = Absolutepath; if (File.separatorChar == '\\') newAbsolutePath = Absolutepath.replace('\\', '/'); saxparser.parse("file:///" + newAbsolutePath, handler); assertTrue(compareWithGold(goldFile, outputFile)); }
/** * <p><b>Description:</b> Test the conrefs are handled by the SAXParser.</p> * <p><b>Bug ID:</b> #15</p> * * @author adrian_sorop * * @throws Exception */ public void testSaxParserConref() throws Exception { File ditaFile = new File(TestUtil.getPath("issue-15_1/topics"),"topic2.dita"); assertTrue("UNABLE TO LOAD FILE", ditaFile.exists()); URL url = URLUtil.correct(ditaFile); SAXParserFactory factory = SAXParserFactory.newInstance(); // Ignore the DTD declaration factory.setValidating(false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/validation", false); SAXParser parser = factory.newSAXParser(); SaxContentHandler handler= new SaxContentHandler(url); parser.parse(ditaFile, handler); List<ReferencedResource> referredFiles = new ArrayList<ReferencedResource>(); referredFiles.addAll(handler.getDitaMapHrefs()); assertEquals("Two files should have been referred.", 2, referredFiles.size()); assertTrue("Should be a content reference to topicConref.dita but was" + referredFiles.get(1).getLocation(), referredFiles.get(1).getLocation().toString().contains("issue-15_1/topics/topicConref.dita")); assertTrue("Should be a xref to topic3.dita", referredFiles.get(0).getLocation().toString().contains("issue-15_1/topics/topic3.dita")); }
/** * Test with valid input source, parser should parse the XML document * successfully. * * @param saxparser a SAXParser instance. * @throws Exception If any errors occur. */ @Test(dataProvider = "parser-provider") public void testParse25(SAXParser saxparser) throws Exception { try (FileInputStream instream = new FileInputStream( new File(XML_DIR, "parsertest.xml"))) { saxparser.parse(instream, new DefaultHandler(), new File(XML_DIR).toURI().toASCIIString()); } }
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception { StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer(); documentSerializer.setOutputStream(finf); SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax); reader.setContentHandler(saxTostax); if (workingDirectory != null) { reader.setEntityResolver(createRelativePathResolver(workingDirectory)); } reader.parse(new InputSource(xml)); xml.close(); finf.close(); }
private static SAXParser allowFileAccess(SAXParser saxParser, boolean disableSecureProcessing) throws SAXException { // if feature secure processing enabled, nothing to do, file is allowed, // or user is able to control access by standard JAXP mechanisms if (disableSecureProcessing) { return saxParser; } try { saxParser.setProperty(ACCESS_EXTERNAL_SCHEMA, "file"); LOGGER.log(Level.FINE, Messages.format(Messages.JAXP_SUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA)); } catch (SAXException ignored) { // nothing to do; support depends on version JDK or SAX implementation LOGGER.log(Level.CONFIG, Messages.format(Messages.JAXP_UNSUPPORTED_PROPERTY, ACCESS_EXTERNAL_SCHEMA), ignored); } return saxParser; }
/**Parses the XML to fetch parameters. * @param inputFile, source XML * @return true, if XML is successfully parsed. * @throws Exception */ public boolean parseXML(File inputFile,UIComponentRepo componentRepo) throws ParserConfigurationException, SAXException, IOException{ LOGGER.debug("Parsing target XML for separating Parameters"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser; try { factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true); saxParser = factory.newSAXParser(); XMLHandler xmlhandler = new XMLHandler(componentRepo); saxParser.parse(inputFile, xmlhandler); return true; } catch (ParserConfigurationException | SAXException | IOException exception) { LOGGER.error("Parsing failed...",exception); throw exception; } }
/** * Reads a {@link CategoryDataset} from a stream. * * @param in the stream. * * @return A dataset. * * @throws IOException if there is a problem reading the file. */ public static CategoryDataset readCategoryDatasetFromXML(final InputStream in) throws IOException { CategoryDataset result = null; final SAXParserFactory factory = SAXParserFactory.newInstance(); try { final SAXParser parser = factory.newSAXParser(); final CategoryDatasetHandler handler = new CategoryDatasetHandler(); parser.parse(in, handler); result = handler.getDataset(); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e2) { System.out.println(e2.getMessage()); } return result; }
@Test public void testInstance() throws ParserConfigurationException, SAXException, IOException { System.out.println(Bug6963468Test.class.getResource("Bug6963468.xsd").getPath()); File schemaFile = new File(Bug6963468Test.class.getResource("Bug6963468.xsd").getPath()); SAXParser parser = createParser(schemaFile); try { parser.parse(Bug6963468Test.class.getResource("Bug6963468.xml").getPath(), new DefaultHandler()); } catch (SAXException e) { e.printStackTrace(); Assert.fail("Fatal Error: " + strException(e)); } }
protected static SAXParser createParser() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser parser = spf.newSAXParser(); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); return parser; }
/** * Find the line number of a target in an Ant script, or some other line in an XML file. * Able to find a certain element with a certain attribute matching a given value. * See also AntTargetNode.TargetOpenCookie. * @param file an Ant script or other XML file * @param match the attribute value to match (e.g. target name) * @param elementLocalName the (local) name of the element to look for * @param elementAttributeName the name of the attribute to match on * @return the line number (0-based), or -1 if not found */ static final int findLine(FileObject file, final String match, final String elementLocalName, final String elementAttributeName) throws IOException, SAXException, ParserConfigurationException { InputSource in = new InputSource(file.getURL().toString()); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); final int[] line = new int[] {-1}; class Handler extends DefaultHandler { private Locator locator; public void setDocumentLocator(Locator l) { locator = l; } public void startElement(String uri, String localname, String qname, Attributes attr) throws SAXException { if (line[0] == -1) { if (localname.equals(elementLocalName) && match.equals(attr.getValue(elementAttributeName))) { // NOI18N line[0] = locator.getLineNumber() - 1; } } } } parser.parse(in, new Handler()); return line[0]; }
private static void receiveXMLStream(final InputStream inStream, final DefaultHandler defHandler) throws ParserConfigurationException, SAXException, IOException { // ... SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser saxParser = spf.newSAXParser(); try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws SAXException, IOException { saxParser.parse(inStream, defHandler); return null; } }, RESTRICTED_ACCESS_CONTROL); // From nested class } catch (PrivilegedActionException pae) { System.out.println("Filesystem access blocked"); pae.printStackTrace(); } }
/** * Testing set MaxOccursLimit to 10000 in the secure processing enabled for * SAXParserFactory. * * @throws Exception If any errors occur. */ @Test public void testMaxOccurLimitPos() throws Exception { String schema_file = XML_DIR + "toys.xsd"; String xml_file = XML_DIR + "toys.xml"; SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setFeature(FEATURE_SECURE_PROCESSING, true); setSystemProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000)); SAXParser parser = factory.newSAXParser(); parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file)); try (InputStream is = new FileInputStream(xml_file)) { MyErrorHandler eh = new MyErrorHandler(); parser.parse(is, eh); assertFalse(eh.isAnyError()); } }
private BeansXml readBeansXml(BeanArchive beanArchive, ClasspathResource resource) { try { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); final SAXParser parser = factory.newSAXParser(); final InputSource source = new InputSource(new ByteArrayInputStream(resource.getBytes())); if (source.getByteStream().available() == 0) { // The file is just acting as a marker file return EMPTY_BEANS_XML; } final BeansXmlHandler handler = new BeansXmlHandler(beanArchive.getClasspathEntry().getURL()); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", loadXsds()); parser.parse(source, handler); return handler.createBeansXml(); } catch (final SAXException | ParserConfigurationException | IOException e) { throw new TestEEfiException( "Failed to parse META-INF/beans.xml in " + beanArchive.getClasspathEntry().getURL(), e ); } }
/** * Unit test for entityResolver setter. * * @throws Exception If any errors occur. */ public void testResolver() throws Exception { String outputFile = USER_DIR + "EntityResolver.out"; String goldFile = GOLDEN_DIR + "EntityResolverGF.out"; String xmlFile = XML_DIR + "publish.xml"; Files.copy(Paths.get(XML_DIR + "publishers.dtd"), Paths.get(USER_DIR + "publishers.dtd"), REPLACE_EXISTING); Files.copy(Paths.get(XML_DIR + "familytree.dtd"), Paths.get(USER_DIR + "familytree.dtd"), REPLACE_EXISTING); try(FileInputStream instream = new FileInputStream(xmlFile); MyEntityResolver eResolver = new MyEntityResolver(outputFile)) { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setEntityResolver(eResolver); InputSource is = new InputSource(instream); xmlReader.parse(is); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Parses a set of styles from <code>inputStream</code>, adding the * resulting styles to the passed in DefaultSynthStyleFactory. * Resources are resolved either from a URL or from a Class. When calling * this method, one of the URL or the Class must be null but not both at * the same time. * * @param inputStream XML document containing the styles to read * @param factory DefaultSynthStyleFactory that new styles are added to * @param urlResourceBase the URL used to resolve any resources, such as Images * @param classResourceBase the Class used to resolve any resources, such as Images * @param defaultsMap Map that UIDefaults properties are placed in */ public void parse(InputStream inputStream, DefaultSynthStyleFactory factory, URL urlResourceBase, Class<?> classResourceBase, Map<String, Object> defaultsMap) throws ParseException, IllegalArgumentException { if (inputStream == null || factory == null || (urlResourceBase == null && classResourceBase == null)) { throw new IllegalArgumentException( "You must supply an InputStream, StyleFactory and Class or URL"); } assert(!(urlResourceBase != null && classResourceBase != null)); _factory = factory; _classResourceBase = classResourceBase; _urlResourceBase = urlResourceBase; _defaultsMap = defaultsMap; try { try { SAXParser saxParser = SAXParserFactory.newInstance(). newSAXParser(); saxParser.parse(new BufferedInputStream(inputStream), this); } catch (ParserConfigurationException e) { throw new ParseException("Error parsing: " + e, 0); } catch (SAXException se) { throw new ParseException("Error parsing: " + se + " " + se.getException(), 0); } catch (IOException ioe) { throw new ParseException("Error parsing: " + ioe, 0); } } finally { reset(); } }
private static void parse(Bundle bundle, InputStream is, Collection<PersistenceUnit> punits) { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); try { SAXParser parser = parserFactory.newSAXParser(); JPAHandler handler = new JPAHandler(bundle); parser.parse(is, handler); punits.addAll(handler.getPersistenceUnits()); } catch (Exception e) { throw new RuntimeException("Error parsing persistence unit in bundle " + bundle.getSymbolicName(), e); // NOSONAR } finally { safeClose(is); } }
/** * Create a <code>SAXParser</code> based on the underlying * <code>Xerces</code> version. * @param properties parser specific properties/features * @return an XML Schema/DTD enabled <code>SAXParser</code> */ public static SAXParser newSAXParser(Properties properties) throws ParserConfigurationException, SAXException, SAXNotSupportedException { SAXParserFactory factory = (SAXParserFactory)properties.get("SAXParserFactory"); if (versionNumber == null){ versionNumber = getXercesVersion(); version = Float.parseFloat(versionNumber); } // Note: 2.2 is completely broken (with XML Schema). if (version > 2.1) { configureXerces(factory); return factory.newSAXParser(); } else { SAXParser parser = factory.newSAXParser(); configureOldXerces(parser,properties); return parser; } }
/** * 返回解析器 * Return the SAXParser we will use to parse the input stream. If there * is a problem creating the parser, return <code>null</code>. */ public SAXParser getParser() { // Return the parser we already created (if any) if (parser != null) { return (parser); } // Create a new parser try { parser = getFactory().newSAXParser(); } catch (Exception e) { log.error("Digester.getParser: ", e); return (null); } return (parser); }
/** * Error Handler to capture all error events to output file. Verifies the * output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testEHFatal() throws Exception { String outputFile = USER_DIR + "EHFatal.out"; String goldFile = GOLDEN_DIR + "EHFatalGF.out"; String xmlFile = XML_DIR + "invalid.xml"; try(MyErrorHandler eHandler = new MyErrorHandler(outputFile); FileInputStream instream = new FileInputStream(xmlFile)) { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setErrorHandler(eHandler); InputSource is = new InputSource(instream); xmlReader.parse(is); fail("Parse should throw SAXException"); } catch (SAXException expected) { // This is expected. } // Need close the output file before we compare it with golden file. assertTrue(compareWithGold(goldFile, outputFile)); }
private void verifyXML(byte[] xml) throws IOException, SAXException, ParserConfigurationException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); if (classLoader == null) { classLoader = getClass().getClassLoader(); } final Schema schema; try (InputStream inputStream = ResourceLoader.getResourceAsStream( getClass(), "TechnicalServices.xsd")) { schema = sf.newSchema(new StreamSource(inputStream)); } spf.setSchema(schema); SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); ErrorHandler errorHandler = new MyErrorHandler(); reader.setErrorHandler(errorHandler); reader.parse(new InputSource(new ByteArrayInputStream(xml))); }
@Test public void testSaxParsing() throws ParserConfigurationException, SAXException, IOException { // given byte[] fileAsByteArray = BaseAdmUmTest.getFileAsByteArray( this.getClass(), FILE_TEST); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); assertTrue(spf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); try { // when reader.parse(new InputSource(new ByteArrayInputStream( fileAsByteArray))); fail(); } catch (SAXParseException e) { // then assertThatMaxEntitiesExceeded(e); } }
/** * Load and read the manifest.xml for a Locale. * @param locale_manifest_in * @return */ public Locale load(InputStream locale_manifest_in) { LocaleParser localeParser = new LocaleParser(); try { final SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser sp = spf.newSAXParser(); final XMLReader xr = sp.getXMLReader(); xr.setContentHandler(localeParser); xr.parse(new InputSource(new BufferedInputStream(locale_manifest_in))); } catch (Exception e) { Debug.e(e); } return localeParser.getLocale(); }
/** * <p><b>Description:</b> Verify the attribute collector over DITA map. * Collect referred files non-recursion.</p> * <p><b>Bug ID:</b> #9</p> * * @author adrian_sorop * * @throws Exception */ public void testSaxParser() throws Exception { File ditaFile = new File(rootDir,"rootMap.ditamap"); assertTrue("UNABLE TO LOAD FILE", ditaFile.exists()); URL url = URLUtil.correct(ditaFile); SAXParserFactory factory = SAXParserFactory.newInstance(); // Ignore the DTD declaration factory.setValidating(false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/validation", false); SAXParser parser = factory.newSAXParser(); SaxContentHandler handler= new SaxContentHandler(url); parser.parse(ditaFile, handler); List<ReferencedResource> referredFiles = new ArrayList<ReferencedResource>(); referredFiles.addAll(handler.getDitaMapHrefs()); assertEquals("Two files should have been referred.", 2, referredFiles.size()); assertTrue("Referred topic in dita maps should be topic2.dita", referredFiles.toString().contains("issue-9/topics/topic2.dita")); assertTrue("Referred topic in dita maps should be topic1.dita", referredFiles.toString().contains("issue-9/topics/topic1.dita")); }
/** * Return the SAXParser we will use to parse the input stream. If there is a * problem creating the parser, return <code>null</code>. */ public SAXParser getParser() { // Return the parser we already created (if any) if (parser != null) { return (parser); } // Create a new parser try { parser = getFactory().newSAXParser(); } catch (Exception e) { log.error("Digester.getParser: ", e); return (null); } return (parser); }
@Override protected Void call() throws Exception { Platform.runLater(this.observableList::clear); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); try (ZipFile zipFile = new ZipFile(this.selectedFile)) { int workMax = zipFile.size(); long workDone = 0; for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry zipEntry = e.nextElement(); int position = zipEntry.getName().charAt(zipEntry.getName().length() - 7) - '0'; SyantenAnalyzer analyzer = new SyantenAnalyzer(position); ParseHandler parseHandler = new ParseHandler(analyzer); try (InputStream is = zipFile.getInputStream(zipEntry); GZIPInputStream gzis = new GZIPInputStream(is)) { saxParser.parse(gzis, parseHandler); } ArrayList<MahjongScene> scenes = analyzer.getOriScenes(); workDone++; Platform.runLater(() -> observableList.addAll(scenes)); updateMessage(workDone + "/" + workMax); updateProgress(workDone, workMax); } } return null; }
/** * Creates the image for the given display XML input source. (Note: The XML is an encoded * mxGraphView, not mxGraphModel.) * * @param inputSource Input source that contains the display XML. * @return Returns an image representing the display XML input source. */ public static BufferedImage convert(InputSource inputSource, mxGraphViewImageReader viewReader) throws ParserConfigurationException, SAXException, IOException { BufferedImage result = null; SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(viewReader); reader.parse(inputSource); if (viewReader.getCanvas() instanceof mxImageCanvas) { result = ((mxImageCanvas) viewReader.getCanvas()).destroy(); } return result; }
/** * Loads completions from an XML input stream. The XML should validate * against <code>CompletionXml.dtd</code>. * * @param in The input stream to read from. * @param cl The class loader to use when loading any extra classes defined * in the XML, such as custom {@link FunctionCompletion}s. This * may be <code>null</code> if the default is to be used, or if no * custom completions are defined in the XML. * @throws IOException If an IO error occurs. */ public void loadFromXML(InputStream in, ClassLoader cl) throws IOException { //long start = System.currentTimeMillis(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); CompletionXMLParser handler = new CompletionXMLParser(this, cl); BufferedInputStream bin = new BufferedInputStream(in); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(bin, handler); List<Completion> completions = handler.getCompletions(); addCompletions(completions); char startChar = handler.getParamStartChar(); if (startChar!=0) { char endChar = handler.getParamEndChar(); String sep = handler.getParamSeparator(); if (endChar!=0 && sep!=null && sep.length()>0) { // Sanity setParameterizedCompletionParams(startChar, sep, endChar); } } } catch (SAXException se) { throw new IOException(se.toString()); } catch (ParserConfigurationException pce) { throw new IOException(pce.toString()); } finally { //long time = System.currentTimeMillis() - start; //System.out.println("XML loaded in: " + time + "ms"); bin.close(); } }
/** * Return the SAXParser we will use to parse the input stream. If there * is a problem creating the parser, return <code>null</code>. */ public SAXParser getParser() { // Return the parser we already created (if any) if (parser != null) { return (parser); } // Create a new parser try { parser = getFactory().newSAXParser(); } catch (Exception e) { log.error("Digester.getParser: ", e); return (null); } return (parser); }
/** * Test an identity transform of an XML document with NS decls using a * non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to * FALSE and prefixes to TRUE. */ @Test public void testXMLNoNsAwareStreamResult2() { try { // Create SAX parser *without* enabling ns SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(false); // Same as default spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser sp = spf.newSAXParser(); // Make sure that the output is well formed String xml = runTransform(sp); checkWellFormedness(xml); } catch (Throwable ex) { Assert.fail(ex.toString()); } }
/** * Parses input stream as an RSS 2.0 feed. * * @return in-memory representation of an RSS feed * @throws IllegalArgumentException if either argument is {@code null} */ private RSSFeed parse(SAXParser parser, InputStream feed) throws SAXException, IOException { if (parser == null) { throw new IllegalArgumentException("RSS parser must not be null."); } else if (feed == null) { throw new IllegalArgumentException("RSS feed must not be null."); } // SAX automatically detects the correct character encoding from the stream // See also http://www.w3.org/TR/REC-xml/#sec-guessing final InputSource source = new InputSource(feed); final XMLReader xmlreader = parser.getXMLReader(); final RSSHandler handler = new RSSHandler(config); xmlreader.setContentHandler(handler); xmlreader.parse(source); return handler.feed(); }
@Test public void testSAX() { try { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(_xsd)); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); spf.setSchema(schema); SAXParser parser = spf.newSAXParser(); MyErrorHandler errorHandler = new MyErrorHandler(); parser.parse(_xml, errorHandler); if (!errorHandler.errorOccured) { Assert.fail("should report error"); } } catch (Exception e) { System.out.println(e.getMessage()); } }
/** * Reads a {@link PieDataset} from a stream. * * @param in the input stream. * * @return A dataset. * * @throws IOException if there is an I/O error. */ public static PieDataset readPieDatasetFromXML(final InputStream in) throws IOException { PieDataset result = null; final SAXParserFactory factory = SAXParserFactory.newInstance(); try { final SAXParser parser = factory.newSAXParser(); final PieDatasetHandler handler = new PieDatasetHandler(); parser.parse(in, handler); result = handler.getDataset(); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e2) { System.out.println(e2.getMessage()); } return result; }
/** * Reads a {@link PieDataset} from a stream. * * @param in the input stream. * * @return A dataset. * * @throws IOException if there is an I/O error. */ public static PieDataset readPieDatasetFromXML(InputStream in) throws IOException { PieDataset result = null; SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); PieDatasetHandler handler = new PieDatasetHandler(); parser.parse(in, handler); result = handler.getDataset(); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e2) { System.out.println(e2.getMessage()); } return result; }