org.xml.sax.XMLReader Java Examples

The following examples show how to use org.xml.sax.XMLReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DTMManagerDefault.java    From jdk8u60 with GNU General Public License v2.0 7 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example #2
Source File: UnmarshallerImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #3
Source File: DTMManagerDefault.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.overrideDefaultParser());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example #4
Source File: Filter.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parse and load the given filter file.
 *
 * @param fileName
 *            name of the filter file
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private void parse(String fileName, @WillClose InputStream stream) throws IOException, SAXException, ParserConfigurationException {
    try {
        SAXBugCollectionHandler handler = new SAXBugCollectionHandler(this, new File(fileName));
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        parserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
        parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
        parserFactory.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
        parserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader xr = parser.getXMLReader();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        Reader reader = Util.getReader(stream);
        xr.parse(new InputSource(reader));
    } finally {
        Util.closeSilently(stream);
    }
}
 
Example #5
Source File: TrAXFilter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void parse (InputSource input) throws SAXException, IOException
{
    XMLReader managedReader = null;

    try {
        if (getParent() == null) {
            try {
                managedReader = XMLReaderManager.getInstance(_useServicesMechanism)
                                                .getXMLReader();
                setParent(managedReader);
            } catch (SAXException  e) {
                throw new SAXException(e.toString());
            }
        }

        // call parse on the parent
        getParent().parse(input);
    } finally {
        if (managedReader != null) {
            XMLReaderManager.getInstance(_useServicesMechanism).releaseXMLReader(managedReader);
        }
    }
}
 
Example #6
Source File: XMLReaderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testLegacy() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

        // set TCCL and try locating the provider
        Thread.currentThread().setContextClassLoader(loader);
        XMLReader reader1 = XMLReaderFactory.createXMLReader();
        assertEquals(reader1.getClass().getName(), "xp3.XMLReaderImpl");

        // now point to a random URL
        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
        // ClassNotFoundException if also trying to load class of reader1, which
        // would be the case before 8152912
        XMLReader reader2 = XMLReaderFactory.createXMLReader();
        assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example #7
Source File: HftpFileSystem.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection("/listPaths" + path,
        "ugi=" + ugi + (recur? "&recursive=yes" : ""));
    connection.setRequestMethod("GET");
    connection.connect();

    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example #8
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
	if (logger.isDebugEnabled()) {
		logger.debug("Setting validation schema to " +
				StringUtils.arrayToCommaDelimitedString(this.schemaResources));
	}
	Assert.notEmpty(resources, "No resources given");
	Assert.hasLength(schemaLanguage, "No schema language provided");
	Source[] schemaSources = new Source[resources.length];
	XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		Assert.isTrue(resource != null && resource.exists(), () -> "Resource does not exist: " + resource);
		InputSource inputSource = SaxResourceUtils.createInputSource(resource);
		schemaSources[i] = new SAXSource(xmlReader, inputSource);
	}
	SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
	if (this.schemaResourceResolver != null) {
		schemaFactory.setResourceResolver(this.schemaResourceResolver);
	}
	return schemaFactory.newSchema(schemaSources);
}
 
Example #9
Source File: XmlToExiConverter.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
protected void decode(String fileName) {
        try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, EXI_EXTENSION));
                OutputStream os = FileUtils.openOutputStream(getFile(fileName, XML_EXTENSION_2))) {

            Reader reader = new InputStreamReader(exiIS,"ISO-8859-1");
            InputSource is = new InputSource(reader);
            is.setEncoding("ISO-8859-1");

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();

            EXISource exiSource = new EXISource();
            XMLReader exiReader = exiSource.getXMLReader();
            SAXSource saxSource = new SAXSource(is);
//            SAXSource saxSource = new SAXSource(new InputSource(exiIS));
            exiSource.setXMLReader(exiReader);
            transformer.transform(saxSource, new StreamResult(os));
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
    }
 
Example #10
Source File: Parser.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses a stylesheet and builds the internal abstract syntax tree
 * @param input A SAX2 InputSource can be passed to a SAX reader
 * @return The root of the abstract syntax tree
 */
public SyntaxTreeNode parse(InputSource input) {
    final XMLReader reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
            _xsltc.isSecureProcessing());

    JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
            _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);

    String lastProperty = "";
    try {
        XMLSecurityManager securityManager =
                (XMLSecurityManager) _xsltc.getProperty(XalanConstants.SECURITY_MANAGER);
        for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
            lastProperty = limit.apiProperty();
            reader.setProperty(lastProperty, securityManager.getLimitValueAsString(limit));
        }
        if (securityManager.printEntityCountInfo()) {
            lastProperty = XalanConstants.JDK_ENTITY_COUNT_INFO;
            reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
        }
    } catch (SAXException se) {
        XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
    }

    return (parse(reader, input));
}
 
Example #11
Source File: UIMAFramework_impl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the factoryConfig.xml file and sets up the ResourceFactory, ResourceSpecifierFactory,
 * and XMLParser.
 * 
 * @throws ParserConfigurationException
 *           if the XML parser could not be configured
 * @throws SAXException
 *           if factoryConfig.xml could not be parsed
 * @throws ClassNotFoundException -
 * @throws IllegalAccessException -
 * @throws InstantiationException -
 * @throws IOException -
 */
protected void parseFactoryConfig() throws ParserConfigurationException, SAXException,
        IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
  FactoryConfigParseHandler handler = new FactoryConfigParseHandler();
  // TOOD: Need UtilityClassLoader here? I don't think we do; this works
  // with XML4J v3. This is a good thing, since the UtilityClassLoader writes
  // to the logger, which isn't created yet!

  SAXParserFactory factory = XMLUtils.createSAXParserFactory();
  SAXParser parser = factory.newSAXParser();
  XMLReader reader = parser.getXMLReader();

  reader.setContentHandler(handler);
  reader.setErrorHandler(handler);
  reader
          .parse(new InputSource(UIMAFramework_impl.class
                  .getResourceAsStream("factoryConfig.xml")));
}
 
Example #12
Source File: DTMManagerDefault.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example #13
Source File: UnmarshallerImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #14
Source File: Digester.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Return the XMLReader to be used for parsing the input document.
 *
 * FIX ME: there is a bug in JAXP/XERCES that prevent the use of a 
 * parser that contains a schema with a DTD.
 * @exception SAXException if no XMLReader can be instantiated
 */
public XMLReader getXMLReader() throws SAXException {
    if (reader == null){
        reader = getParser().getXMLReader();
    }        
                           
    reader.setDTDHandler(this);           
    reader.setContentHandler(this);        
    
    if (entityResolver == null){
        reader.setEntityResolver(this);
    } else {
        reader.setEntityResolver(entityResolver);           
    }
    
    reader.setProperty(
            "http://xml.org/sax/properties/lexical-handler", this);

    reader.setErrorHandler(this);
    return reader;
}
 
Example #15
Source File: BackendManager.java    From uPods-android with Apache License 2.0 6 votes vote down vote up
public ArrayList<Episode> fetchEpisodes(String feedUrl, Podcast podcast) {
    try {
        Request request = new Request.Builder().url(feedUrl).build();
        String response = BackendManager.getInstance().sendSimpleSynchronicRequest(request);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
        xr.setContentHandler(episodesXMLHandler);

        //TODO could be encoding problem
        InputSource inputSource = new InputSource(new StringReader(response));
        xr.parse(inputSource);
        ArrayList<Episode> parsedEpisodes = episodesXMLHandler.getParsedEpisods();
        if (podcast != null) {
            podcast.setDescription(episodesXMLHandler.getPodcastSummary());
        }
        return parsedEpisodes;
    } catch (Exception e) {
        Logger.printError(TAG, "Can't fetch episodes for url: " + feedUrl);
        e.printStackTrace();
        return new ArrayList<Episode>();
    }
}
 
Example #16
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        // I have put this as it was complaining about systemid
        thandler.setSystemId("file:///" + USER_DIR);

        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        XMLFilter filter
                = saxTFactory.newXMLFilter(thandler.getTemplates());
        filter.setParent(reader);

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #17
Source File: Analyzer.java    From vi with Apache License 2.0 5 votes vote down vote up
public static PomInfo readPom(InputStream is) throws SAXException, IOException {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);
        PomDependencyHandler handler = new PomDependencyHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(is));
        return handler.getPomInfo();
    }
 
Example #18
Source File: EXIficientDemo.java    From exificient with MIT License 5 votes vote down vote up
protected void decode(XMLReader exiReader, String exiLocation)
		throws SAXException, IOException, TransformerException {

	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();

	InputStream exiIS = new FileInputStream(exiLocation);
	SAXSource exiSource = new SAXSource(new InputSource(exiIS));
	exiSource.setXMLReader(exiReader);

	OutputStream os = new FileOutputStream(exiLocation + XML_EXTENSION);
	transformer.transform(exiSource, new StreamResult(os));
	os.close();
}
 
Example #19
Source File: JAXPXMLReaderCreator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see com.sun.xml.internal.rngom.xml.sax.XMLReaderCreator#createXMLReader()
 */
public XMLReader createXMLReader() throws SAXException {
    try {
        return spf.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
}
 
Example #20
Source File: PropertiesXmlLoader.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void load(final Properties p, InputStream in) throws IOException,
        InvalidPropertiesFormatException {
    if (in == null) {
        throw new NullPointerException("in == null");
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(new DefaultHandler() {
            private String key;

            @Override
            public void startElement(String uri, String localName,
                    String qName, Attributes attributes) throws SAXException {
                key = null;
                if (qName.equals("entry")) {
                    key = attributes.getValue("key");
                }
            }

            @Override
            public void characters(char[] ch, int start, int length)
                    throws SAXException {
                if (key != null) {
                    String value = new String(ch, start, length);
                    p.put(key, value);
                    key = null;
                }
            }
        });
        reader.parse(new InputSource(in));
    } catch (SAXException e) {
        throw new InvalidPropertiesFormatException(e);
    }
}
 
Example #21
Source File: XMLReaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * XMLReader.getProperty returns null if DECL_HANDLER wasn't set.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void xrProperty04() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    assertNull(xmlReader.getProperty(DECL_HANDLER));
}
 
Example #22
Source File: AbstractUnmarshallerImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private Object unmarshal( SAXSource source ) throws JAXBException {

        XMLReader r = source.getXMLReader();
        if( r == null )
            r = getXMLReader();

        return unmarshal( r, source.getInputSource() );
    }
 
Example #23
Source File: XMLConfigReader.java    From cms with Apache License 2.0 5 votes vote down vote up
public CmsConfiguration readConfiguration(InputStream is) throws Exception 
{
	SAXParserFactory spf = SAXParserFactory.newInstance();
	spf.setNamespaceAware(true);
	SAXParser saxParser = spf.newSAXParser();
	XMLReader xmlReader = saxParser.getXMLReader();
	XMLConfigContentHandler contentHandler = new XMLConfigContentHandler();
	xmlReader.setContentHandler(contentHandler);
	xmlReader.parse(new InputSource(is));
	return contentHandler.getConfiguration();
}
 
Example #24
Source File: AutomaticDependencies.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * The recognizer entry method taking an InputSource.
 * @param input InputSource to be parsed.
 * @throws IOException on I/O error.
 * @throws SAXException propagated exception thrown by a DocumentHandler.
 */
public void parse(final InputSource input) throws SAXException, IOException {
    XMLReader parser = XMLUtil.createXMLReader(false, false); // fastest mode
    parser.setContentHandler(this);
    parser.setErrorHandler(this);
    parser.setEntityResolver(this);
    parser.parse(input);
}
 
Example #25
Source File: XmlResourceBundle.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a property resource bundle.
 * @param filelocation location of XML file to parse
 * @throws IOException if the file can't be parsed/loaded
 */
public XmlResourceBundle(String filelocation) throws IOException {
    strings = new HashMap<String, String>();
    try {
        // These are namespace URLs, and don't actually
        // resolve to real documents that get downloaded on the
        // web.
        // Turn on validation
        String validationFeature
            = "http://xml.org/sax/features/validation";
        // Turn on schema validation
        String schemaFeature
            = "http://apache.org/xml/features/validation/schema";
        // We have to store the xsd locally because we may not have
        // access to it over the web when starting up the service.
        String xsdLocation =
            this.getClass().getResource("/xliff-core-1.1.xsd").toString();
        XMLReader parser = XMLReaderFactory.
            createXMLReader("org.apache.xerces.parsers.SAXParser");
        parser.setFeature(validationFeature, false);
        parser.setFeature(schemaFeature, false);
        parser.setProperty("http://apache.org/xml/properties/schema/" +
                "external-noNamespaceSchemaLocation", xsdLocation);
        XmlResourceBundleParser handler = new XmlResourceBundleParser();
        parser.setContentHandler(handler);
        parser.parse(new InputSource(this.getClass().
                                     getResourceAsStream(filelocation)));
        strings = handler.getMessages();
    }
    catch (SAXException e) {
        // This really should never happen, because without this file,
        // the whole UI stops working.
        log.error("Could not setup parser");
        throw new IOException("Could not load XML bundle: " + filelocation);
    }
    // TODO: put the xml strings in the Map

}
 
Example #26
Source File: Bug4970951.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    XMLReader xmlReader = createXMLReader();
    final ValidatorHandler validatorHandler = createValidatorHandler(XSD);
    xmlReader.setContentHandler(validatorHandler);

    DefaultHandler handler = new DefaultHandler() {
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (!"ns:test".equals(qName)) {
                return;
            }

            TypeInfoProvider infoProvider = validatorHandler.getTypeInfoProvider();
            if (infoProvider == null) {
                throw new SAXException("Can't obtain TypeInfoProvider object.");
            }

            int index = attributes.getIndex("id");
            if (index == -1) {
                throw new SAXException("The attribute 'id' is not in the list.");
            }

            Assert.assertTrue(infoProvider.isSpecified(index));

            index = attributes.getIndex("date");
            if (index == -1) {
                throw new SAXException("The attribute 'date' is not in the list.");
            }

            Assert.assertFalse(infoProvider.isSpecified(index));

            System.out.println("OK");
        }
    };
    validatorHandler.setContentHandler(handler);

    parse(xmlReader, XML);
}
 
Example #27
Source File: SAXParseable.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static InputSource makeInputSource(XMLReader xr, String systemId) throws IOException, SAXException {
  EntityResolver er = xr.getEntityResolver();
  if (er != null) {
    InputSource inputSource = er.resolveEntity(null, systemId);
    if (inputSource != null)
  return inputSource;
  }
  return new InputSource(systemId);
}
 
Example #28
Source File: SelfContainedTestCase.java    From exificient with MIT License 5 votes vote down vote up
public static void main(String[] args) throws EXIException, IOException,
		SAXException {
	String xml = "./data/W3C/PrimerNotebook/notebook.xml";
	// String xsd = "./data/W3C/PrimerNotebook/notebook.xsd";

	EXIFactory factory = DefaultEXIFactory.newInstance();
	// factory.setGrammars(GrammarFactory.newInstance().createGrammars(xsd));
	factory.setFidelityOptions(FidelityOptions.createDefault());
	// factory.setCodingMode(CodingMode.BIT_PACKED);
	FidelityOptions fo = factory.getFidelityOptions();
	fo.setFidelity(FidelityOptions.FEATURE_SC, true);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	QName sc = new QName("", "note");
	// QName sc = new QName(".*", ".*"); // any

	QName[] scElements = new QName[1];
	scElements[0] = sc;
	SelfContainedHandlerTracker scHandler = new SelfContainedHandlerTracker();
	factory.setSelfContainedElements(scElements, scHandler);

	EXIResult exiResult = new EXIResult(factory);
	exiResult.setOutputStream(baos);
	XMLReader xmlReader = XMLReaderFactory.createXMLReader();
	xmlReader.setContentHandler(exiResult.getHandler());
	xmlReader.parse(new InputSource(new FileInputStream(xml)));

	for (int i = 0; i < scHandler.getSCIndices().size(); i++) {
		System.out.println(scHandler.getSCQNames().get(i) + ": "
				+ scHandler.getSCIndices().get(i) + " bytes");
	}

	// OutputStream os = new FileOutputStream("./out/notebook.xml.exi-sc");
	// os.write(baos.toByteArray());
	// os.close();
}
 
Example #29
Source File: Notices.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * Reads known notices from an XML file.
 * 
 * @param inputStream an input stream to read the file contents from
 * @param validateXml true if the XML content read should be validated, false otherwise
 * @param log the logger
 * @throws IOException
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public void readNotices(final InputStream inputStream, boolean validateXml, final ILSLog log)
        throws IOException, ParserConfigurationException, SAXException {

    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(validateXml);
    final SAXParser saxParser = spf.newSAXParser();
    final XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new NoticeSaxHandler(log));
    xmlReader.parse(MiscUtil.getInputSource(inputStream));
}
 
Example #30
Source File: RsPrettyXml.java    From takes with MIT License 5 votes vote down vote up
/**
 * Format body with proper indents using SAX.
 * @param body Response body
 * @return New properly formatted body
 * @throws IOException If fails
 */
private static byte[] transform(final InputStream body) throws IOException {
    final SAXSource source = new SAXSource(new InputSource(body));
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        final XMLReader xmlreader = SAXParserFactory.newInstance()
            .newSAXParser().getXMLReader();
        source.setXMLReader(xmlreader);
        xmlreader.setFeature(
            RsPrettyXml.LOAD_EXTERNAL_DTD, false
        );
        final String yes = "yes";
        final Transformer transformer = TransformerFactory.newInstance()
            .newTransformer();
        // @checkstyle MultipleStringLiteralsCheck (2 line)
        transformer.setOutputProperty(
            OutputKeys.OMIT_XML_DECLARATION, yes
        );
        RsPrettyXml.prepareDocType(body, transformer);
        transformer.setOutputProperty(OutputKeys.INDENT, yes);
        transformer.transform(source, new StreamResult(result));
    } catch (final TransformerException
        | ParserConfigurationException
        | SAXException ex) {
        throw new IOException(ex);
    }
    return result.toByteArray();
}