/** * 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()); } }
@Test public final void testLargeMaxOccurs() { String XML_FILE_NAME = "Bug4674384_MAX_OCCURS_Test.xml"; try { // create and initialize the parser 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"); File xmlFile = new File(getClass().getResource(XML_FILE_NAME).getPath()); parser.parse(xmlFile, new DefaultHandler()); } catch (Exception e) { System.err.println("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs."); e.printStackTrace(); Assert.fail("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs. " + e.getMessage()); } System.out.println("Success: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs."); }
/** * Test the default functionality of schema support method. In * this case the schema source property is set. * @throws Exception If any errors occur. */ @Test(dataProvider = "schema-source") public void testCheckSchemaSupport3(Object schemaSource) throws Exception { try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(true); spf.setNamespaceAware(true); SAXParser sp = spf.newSAXParser(); sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", W3C_XML_SCHEMA_NS_URI); sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource); DefaultHandler dh = new DefaultHandler(); // Not expect any unrecoverable error here. sp.parse(new File(XML_DIR, "test1.xml"), dh); } finally { if (schemaSource instanceof Closeable) { ((Closeable) schemaSource).close(); } } }
public static void parse( URL xmlURL, URL schema, DefaultHandler handler) throws SAXException, IOException, ParserConfigurationException { InputStream xmlStream = URLHandlerRegistry.getDefault().openStream(xmlURL); try { InputSource inSrc = new InputSource(xmlStream); inSrc.setSystemId(xmlURL.toExternalForm()); parse(inSrc, schema, handler); } finally { try { xmlStream.close(); } catch (IOException e) { // ignored } } }
/** * 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]; }
/** Creates a new instance of BinaryInputArchive */ public XmlInputArchive(InputStream in) throws ParserConfigurationException, SAXException, IOException { valList = new ArrayList<Value>(); DefaultHandler handler = new XMLParser(valList); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(in, handler); vLen = valList.size(); vIdx = 0; }
public static void parse(DefaultHandler handler, String file) throws SAXException, IOException { XMLReader xreader = XMLReaderFactory.createXMLReader(); xreader.setContentHandler(handler); xreader.setErrorHandler(handler); FileReader reader = new FileReader(file); xreader.parse(new InputSource(reader)); }
private void processFullCreoleXmlTree(Plugin plugin, Document jdomDoc, CreoleAnnotationHandler annotationHandler) throws GateException, IOException, JDOMException { // now we can process any annotations on the new classes // and augment the XML definition annotationHandler.processAnnotations(jdomDoc); // debugging if(DEBUG) { XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(jdomDoc, System.out); } // finally, parse the augmented definition with the normal parser DefaultHandler handler = new CreoleXmlHandler(this, plugin); SAXOutputter outputter = new SAXOutputter(handler, handler, handler, handler); outputter.output(jdomDoc); if(DEBUG) { Out.prln("done parsing " + plugin); } }
private QName determineFeatureTypeSchema(File file) { try { GML2Handler handler = new GML2Handler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.newSAXParser().parse(new FileInputStream(file), (DefaultHandler) handler); String schemaUrl = handler.getSchemaUrl(); if (schemaUrl == null) { return null; } String namespaceURI = handler.getNameSpaceURI(); return new QName(namespaceURI, schemaUrl); } catch (Exception e) { LOGGER.error("Exception while trying to determine schema of FeatureType.", e); throw new IllegalArgumentException(e); } }
private QName determineFeatureTypeSchema(File file) { try { GML2Handler handler = new GML2Handler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.newSAXParser().parse(new FileInputStream(file), (DefaultHandler) handler); String schemaUrl = handler.getSchemaUrl(); String namespaceURI = handler.getNameSpaceURI(); return new QName(namespaceURI, schemaUrl); } catch (Exception e) { LOGGER.error( "Exception while trying to determining GML2 FeatureType schema.", e); throw new IllegalArgumentException(e); } }
/** * Parse the content given {@link org.xml.sax.InputSource} * as XML using the specified * {@link org.xml.sax.helpers.DefaultHandler}. * * @param is The InputSource containing the content to be parsed. * @param dh The SAX DefaultHandler to use. * * @throws IllegalArgumentException If the <code>InputSource</code> object * is <code>null</code>. * @throws IOException If any IO errors occur. * @throws SAXException If any SAX errors occur during processing. * * @see org.xml.sax.DocumentHandler */ public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException { if (is == null) { throw new IllegalArgumentException("InputSource cannot be null"); } XMLReader reader = this.getXMLReader(); if (dh != null) { reader.setContentHandler(dh); reader.setEntityResolver(dh); reader.setErrorHandler(dh); reader.setDTDHandler(dh); } reader.parse(is); }
/** * The start of an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * @param atts the element attributes. * * @throws SAXException for errors. */ public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException { final DefaultHandler current = getCurrentHandler(); if (current != this) { current.startElement(namespaceURI, localName, qName, atts); } else if (qName.equals(CATEGORYDATASET_TAG)) { this.dataset = new DefaultCategoryDataset(); } else if (qName.equals(SERIES_TAG)) { final CategorySeriesHandler subhandler = new CategorySeriesHandler(this); getSubHandlers().push(subhandler); subhandler.startElement(namespaceURI, localName, qName, atts); } else { throw new SAXException("Element not recognised: " + qName); } }
/** * Starts an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * @param atts the element attributes. * * @throws SAXException for errors. */ public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException { final DefaultHandler current = getCurrentHandler(); if (current != this) { current.startElement(namespaceURI, localName, qName, atts); } else if (qName.equals(PIEDATASET_TAG)) { this.dataset = new DefaultPieDataset(); } else if (qName.equals(ITEM_TAG)) { final ItemHandler subhandler = new ItemHandler(this, this); getSubHandlers().push(subhandler); subhandler.startElement(namespaceURI, localName, qName, atts); } }
/** * The start of an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * @param atts the element attributes. * * @throws SAXException for errors. */ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { DefaultHandler current = getCurrentHandler(); if (current != this) { current.startElement(namespaceURI, localName, qName, atts); } else if (qName.equals(CATEGORYDATASET_TAG)) { this.dataset = new DefaultCategoryDataset(); } else if (qName.equals(SERIES_TAG)) { CategorySeriesHandler subhandler = new CategorySeriesHandler(this); getSubHandlers().push(subhandler); subhandler.startElement(namespaceURI, localName, qName, atts); } else { throw new SAXException("Element not recognised: " + qName); } }
/** * Starts an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * @param atts the element attributes. * * @throws SAXException for errors. */ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { DefaultHandler current = getCurrentHandler(); if (current != this) { current.startElement(namespaceURI, localName, qName, atts); } else if (qName.equals(PIEDATASET_TAG)) { this.dataset = new DefaultPieDataset(); } else if (qName.equals(ITEM_TAG)) { ItemHandler subhandler = new ItemHandler(this, this); getSubHandlers().push(subhandler); subhandler.startElement(namespaceURI, localName, qName, atts); } }
private static void sendToParser(String b) throws Throwable { byte[] input = b.getBytes("UTF-8"); ByteArrayInputStream in = new ByteArrayInputStream(input); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser p = spf.newSAXParser(); p.parse(new InputSource(in), new DefaultHandler()); }
@Test public void testSAXResult() { DefaultHandler handler = new DefaultHandler(); final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"?><root></root>"; try { SAXResult saxResult = new SAXResult(handler); // saxResult.setSystemId("jaxp-ri/unit-test/javax/xml/stream/XMLOutputFactoryTest/cr6846132.xml"); XMLOutputFactory ofac = XMLOutputFactory.newInstance(); XMLStreamWriter writer = ofac.createXMLStreamWriter(saxResult); writer.writeStartDocument("1.0"); writer.writeStartElement("root"); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (Exception e) { if (e instanceof UnsupportedOperationException) { // expected } else { e.printStackTrace(); Assert.fail(e.toString()); } } }
@Test public void testSAXResult1() { DefaultHandler handler = new DefaultHandler(); try { SAXResult saxResult = new SAXResult(handler); XMLOutputFactory ofac = XMLOutputFactory.newInstance(); XMLEventWriter writer = ofac.createXMLEventWriter(saxResult); } catch (Exception e) { if (e instanceof UnsupportedOperationException) { // expected } else { e.printStackTrace(); Assert.fail(e.toString()); } } }
@Test public void test() { try { Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(testFile)); 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 DefaultHandler()); // InputStream input = // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml"); InputStream input = getClass().getResourceAsStream("Issue682.xml"); System.out.println("Parse InputStream:"); xmlReader.parse(new InputSource(input)); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(ex.toString()); } }
@Test public void test() throws Exception { String invalidXml = "<a>"; SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true); SAXParser parser = saxParserFactory.newSAXParser(); parser.parse(new InputSource(new StringReader(invalidXml)), new DefaultHandler() { @Override public void fatalError(SAXParseException e) throws SAXException { System.err.printf("%s%n", e.getMessage()); } }); }
void parse() throws SAXException { String xml = "<data>\n<broken/>\u0000</data>"; try { InputSource is = new InputSource(new StringReader(xml)); is.setSystemId("file:///path/to/some.xml"); // notice that exception thrown here doesn't include the line number // information when reported by JVM -- CR6889654 SAXParserFactory.newInstance().newSAXParser().parse(is, new DefaultHandler()); } catch (SAXException e) { // notice that this message isn't getting displayed -- CR6889649 throw new SAXException(MSG, e); } catch (ParserConfigurationException pce) { } catch (IOException ioe) { } }
public static void parse( InputSource xmlStream, URL schema, DefaultHandler handler) throws SAXException, IOException, ParserConfigurationException { InputStream schemaStream = null; try { if (schema != null) { schemaStream = URLHandlerRegistry.getDefault().openStream(schema); } // Set the context classloader to the bootstrap classloader, to work around how JAXP locates implementation classes // This should ensure that the JAXP classes provided by the JVM are used, rather than some other implementation ClassLoader original = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ClassLoaderUtils.getPlatformClassLoader()); try { SAXParser parser = newSAXParser(schema, schemaStream); parser.parse(xmlStream, handler); } finally { Thread.currentThread().setContextClassLoader(original); } } finally { if (schemaStream != null) { try { schemaStream.close(); } catch (IOException ex) { // ignored } } } }
/** * Parse XML document and validate against CAS schema */ private Document parseAndValidate(String xml) throws Exception { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(getClass().getResource("cas-response-schema.xsd")); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setSchema(schema); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new FatalAdapter(new DefaultHandler())); return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); }
public void testHandlerLeak() throws Exception { ErrorHandler handler = new DefaultHandler(); EntityResolver resolver = new DefaultHandler(); Reference<?> handlerRef = new WeakReference<Object>(handler); Reference<?> resolverRef = new WeakReference<Object>(resolver); XMLUtil.parse(new InputSource(new StringReader("<hello/>")), false, false, handler, resolver); handler = null; resolver = null; assertGC("can collect handler", handlerRef); assertGC("can collect resolver", resolverRef); }
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { String xmlString = "<?xml version=\"1.0\"?>" + "<!DOCTYPE foo SYSTEM \"C:/test\"><test>&foo;</test>"; // Tainted input InputStream is = new ByteArrayInputStream(xmlString.getBytes()); receiveXMLStream(is, new DefaultHandler()); }
private static void _readRegionMetadata( RegionMetadata bean, InputStream in, String publicId) { if (_LOG.isFiner()) { _LOG.finer("Loading region-metadata from file:{0}", publicId); } try { InputSource input = new InputSource(); input.setByteStream(in); input.setPublicId(publicId); DefaultHandler handler = new Handler(bean); _SAX_PARSER_FACTORY.newSAXParser().parse(input, handler); } catch (IOException ioe) { _error(publicId, ioe); } catch (ParserConfigurationException pce) { _error(publicId, pce); } catch (SAXException saxe) { _error(publicId, saxe); } }
/** * Convenience method to examine and parse SOAP response. Caller handles * whatever exception may be thrown. Note that the Content-Type from the * SHEX server will be application/soap+xml, whereas the Content-Type from * MEX will be "text/xml". Accordingly we seek to parse either. * * @param conn * @param inp * @param handler * @param contentType * @return Pair of String, Boolean. The String is an accumulated message * (which may be blank) and the boolean is true (parsed), false * (failed parse) * @throws Exception */ private Pair<String, Boolean> examineSOAPResponse(HttpURLConnection conn, InputStream inp, DefaultHandler handler, String contentType) throws Exception { String responseMessage = ""; boolean parsedResponse = false; String responseContentType = conn.getContentType(); // which ever xml variant the contentType is, "text/xml", // "application/soap+xml" if( responseContentType != null && (responseContentType.toLowerCase().startsWith(contentType) || responseContentType.toLowerCase() .contains(DEFAULT_CONTENT_TYPE)) ) { SAXParser saxParser = factory.newSAXParser(); if( inp != null ) { InputSource inpsrc = new InputSource(inp); inpsrc.setEncoding("UTF-8"); try { saxParser.parse(inpsrc, handler); parsedResponse = true; } catch( Exception parsee ) { // sigh - leave the boolean false and let the caller try as // plain text, but add what error info we have responseMessage += "saxParserException:\n"; responseMessage += parsee.getLocalizedMessage(); responseMessage += '\n'; } } } return new Pair<String, Boolean>(responseMessage, parsedResponse); }
/** Creates a new instance of DocumetParser2 */ public SAXDocumentParser() { DefaultHandler handler = new DefaultHandler(); _attributes = new AttributesHolder(_registeredEncodingAlgorithms); _entityResolver = handler; _dtdHandler = handler; _contentHandler = handler; _errorHandler = handler; _lexicalHandler = new LexicalHandlerImpl(); _declHandler = new DeclHandlerImpl(); }
/** * Cosntructor - pass in reference to a TransformerImpl object */ public TransformerHandlerImpl(TransformerImpl transformer) { // Save the reference to the transformer _transformer = transformer; if (transformer.isIdentity()) { // Set initial handler to the empty handler _handler = new DefaultHandler(); _isIdentity = true; } else { // Get a reference to the translet wrapped inside the transformer _translet = _transformer.getTranslet(); } }
/** * Test case to parse an XML file that not use namespaces. * * @param saxparser a SAXParser instance. * @throws Exception If any errors occur. */ @Test(dataProvider = "parser-provider") public void testParse30(SAXParser saxparser) throws Exception { try (FileInputStream instream = new FileInputStream( new File(XML_DIR, "correct.xml"))) { saxparser.parse(new InputSource(instream), new DefaultHandler()); } }
/** * Converts data from the given <code>InputStream</code> into HTML that is written to the given * <code>PrintWriter</code> */ private static void convert(InputStream in, PrintWriter out) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); DefaultHandler handler = new GenerateMBeanHTML(out); parser.parse(in, handler); }
/** * The end of an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * * @throws SAXException for errors. */ public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { final DefaultHandler current = getCurrentHandler(); if (current != this) { current.endElement(namespaceURI, localName, qName); } }
private static void receiveXMLStream(final InputStream inStream, final DefaultHandler defHandler) throws ParserConfigurationException, SAXException, IOException { // ... SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setEntityResolver(new CustomResolver()); //Custom resolver InputSource is = new InputSource(inStream); reader.parse(is); }
@Test public void testSchemaValidation() throws Exception { SAXParser sp = getValidatingParser(); sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); sp.parse(new File(ASTROCAT), new DefaultHandler()); }
/** * Creates a new item handler. * * @param root the root handler. * @param parent the parent handler. */ public ItemHandler(final RootHandler root, final DefaultHandler parent) { this.root = root; this.parent = parent; this.key = null; this.value = null; }
/** * The end of an element. * * @param namespaceURI the namespace. * @param localName the element name. * @param qName the element name. * * @throws SAXException for errors. */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { DefaultHandler current = getCurrentHandler(); if (current != this) { current.endElement(namespaceURI, localName, qName); } }
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { String xmlString = "<?xml version=\"1.0\"?>" + "<!DOCTYPE test [ <!ENTITY foo SYSTEM \"C:/Code/public.txt\"> ]><test>&foo;</test>"; // Tainted input InputStream is = new ByteArrayInputStream(xmlString.getBytes()); receiveXMLStream(is, new DefaultHandler()); }