Java Code Examples for javax.xml.parsers.SAXParserFactory#newInstance()

The following examples show how to use javax.xml.parsers.SAXParserFactory#newInstance() . 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: Parser.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(true);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
 
Example 2
Source File: UnittypeXML.java    From freeacs with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void load(String file_input) throws Exception {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setXIncludeAware(true);
  factory.setNamespaceAware(false);
  factory.setValidating(false);

  SAXParser parser = factory.newSAXParser();

  SAXReader reader = new SAXReader(parser.getXMLReader());
  Document document = reader.read(file_input);

  info = new Info();
  info.load(document.selectSingleNode("//unittype/info"));

  Enums enums = new Enums();
  enums.load(document.selectSingleNode("//unittype/parameters/enums"));

  parameters = new Parameters();
  List parameters_nodes = document.selectNodes("//unittype/parameters");
  for (Object parameters_node : parameters_nodes) {
    Node parameter_node = (Node) parameters_node;
    parameters.load(parameter_node, enums);
  }
}
 
Example 3
Source File: TMXExtractor.java    From phrasal with GNU General Public License v3.0 6 votes vote down vote up
static public void main(String[] args) throws Exception {
  if (args.length < 3) {
    usage();
    exit(-1);
  }
  
  String tmxFn = args[0];
  String outputPrefixFn = args[1];
  Set<String> langs = new HashSet<String>();
  for (int i = 2; i < args.length; i++) {
    langs.add(args[i]);
  }
  SAXParserFactory saxpf = SAXParserFactory.newInstance();
  SAXParser saxParser = saxpf.newSAXParser();
  saxParser.parse(new File(tmxFn), new TMXExtractor(outputPrefixFn, langs));        
}
 
Example 4
Source File: GroupsXMLLoader.java    From stendhal with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load and returns the list of files.
 *
 * @param in
 *            The config file stream.
 * @return list of group entries
 *
 * @throws SAXException
 *             If a SAX error occurred.
 * @throws IOException
 *             If an I/O error occurred.
 */
protected List<URI> load(final InputStream in) throws SAXException, IOException {
	SAXParser saxParser;

	// Use the default (non-validating) parser
	final SAXParserFactory factory = SAXParserFactory.newInstance();
	try {
		saxParser = factory.newSAXParser();
	} catch (final ParserConfigurationException ex) {
		throw new SAXException(ex);
	}

	// Parse the XML
	groups = new LinkedList<URI>();
	saxParser.parse(in, this);
	return groups;
}
 
Example 5
Source File: Catalog.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Setup readers.
 */
public void setupReaders() {
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(true);
  spf.setValidating(false);

  SAXCatalogReader saxReader = new SAXCatalogReader(spf);

  saxReader.setCatalogParser(null, "XMLCatalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");

  saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
                             "catalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader");

  addReader("application/xml", saxReader);

  TR9401CatalogReader textReader = new TR9401CatalogReader();
  addReader("text/plain", textReader);
}
 
Example 6
Source File: PvXMLHandler.java    From AndrOBD with GNU General Public License v3.0 6 votes vote down vote up
/**
 * main routine for testing class implementation
 *
 * @param argv command line arguments
 */
public static void main(String[] argv)
{
	try
	{
		// Create a new Parser
		PvXMLHandler handler = new PvXMLHandler();
		// Use the default (non-validating) parser
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// Parse the input
		SAXParser saxParser = factory.newSAXParser();
		saxParser.parse(new FileInputStream(argv[0]), handler);
	} catch (Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 7
Source File: XmlRecordInput.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of XmlRecordInput */
public XmlRecordInput(InputStream in) {
  try{
    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;
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 8
Source File: SAXParserDemo2.java    From java with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  SAXParserFactory parserFactor = SAXParserFactory.newInstance();
  SAXParser parser = parserFactor.newSAXParser();
  SAXHandler handler = new SAXHandler();
  parser.parse(ClassLoader.getSystemResourceAsStream("Student.xml"), 
               handler);
}
 
Example 9
Source File: SAXParserFactTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test the functionality of setNamespaceAware and
 * isNamespaceAware methods.
 */
@Test
public void testNamespace02() {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    assertTrue(spf.isNamespaceAware());
}
 
Example 10
Source File: CLDRConverter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static Map<String, Object> getCLDRBundle(String id) throws Exception {
    Map<String, Object> bundle = cldrBundles.get(id);
    if (bundle != null) {
        return bundle;
    }
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    enableFileAccess(parser);
    LDMLParseHandler handler = new LDMLParseHandler(id);
    File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
    if (!file.exists()) {
        // Skip if the file doesn't exist.
        return Collections.emptyMap();
    }

    info("..... main directory .....");
    info("Reading file " + file);
    parser.parse(file, handler);

    bundle = handler.getData();
    cldrBundles.put(id, bundle);
    String country = getCountryCode(id);
    if (country != null) {
        bundle = handlerSuppl.getData(country);
        if (bundle != null) {
            //merge two maps into one map
            Map<String, Object> temp = cldrBundles.remove(id);
            bundle.putAll(temp);
            cldrBundles.put(id, bundle);
        }
    }
    return bundle;
}
 
Example 11
Source File: SpellXMLLoader.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
public Collection<DefaultSpell> load(URI uri) throws SAXException {
	loadedSpells = new LinkedList<DefaultSpell>();
	// Use the default (non-validating) parser
	final SAXParserFactory factory = SAXParserFactory.newInstance();
	try {
		// Parse the input
		final SAXParser saxParser = factory.newSAXParser();

		final InputStream is = SpellXMLLoader.class.getResourceAsStream(uri.getPath());

		if (is == null) {
			throw new FileNotFoundException("cannot find resource '" + uri
					+ "' in classpath");
		}
		try {
			saxParser.parse(is, this);
		} finally {
			is.close();
		}
	} catch (final ParserConfigurationException t) {
		logger.error(t);
	} catch (final IOException e) {
		logger.error(e);
		throw new SAXException(e);
	}
	return loadedSpells;
}
 
Example 12
Source File: TrxBinder.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
@Override
public void process(File source) throws Exception {
	zeroTime = TIME_MILLIS_FORMAT.parse("00:00:00.000");
	SAXParserFactory factory = SAXParserFactory.newInstance();
	SAXParser saxParser = factory.newSAXParser();
	saxParser.parse(source, this);
}
 
Example 13
Source File: XMLReaderAdapter.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
public void parse(DefaultHandler handler, InputStream is) throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    XMLReader xmlReader = factory.newSAXParser().getXMLReader();
    xmlReader.setContentHandler(handler);
    xmlReader.parse(new InputSource(is));
}
 
Example 14
Source File: Bug6359330.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    System.setSecurityManager(new SecurityManager());
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(true);
        SAXParser sp = spf.newSAXParser();
        // The following line shouldn't throw a
        // java.security.AccessControlException.
        sp.setProperty("foo", "bar");
    } catch (SAXNotRecognizedException e) {
        // Ignore this expected exception.
    }
}
 
Example 15
Source File: DefenseInboundAdapter.java    From defense-solutions-proofs-of-concept with Apache License 2.0 5 votes vote down vote up
public DefenseInboundAdapter(AdapterDefinition definition) throws ComponentException, ParserConfigurationException, SAXException, IOException
{
	super(definition);
	messageParser = new MessageParser(this);
	saxFactory = SAXParserFactory.newInstance();
	saxParser = saxFactory.newSAXParser();
}
 
Example 16
Source File: WhitespacesTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "TestSchemaFiles")
public void testWhitespacesCollapse(String schemaFile) throws Exception {
    XSOMParser parser = new XSOMParser(SAXParserFactory.newInstance());
    XsomErrorHandler eh = new XsomErrorHandler();

    parser.setErrorHandler(eh);
    parser.parse(getSchemaFile(schemaFile));

    if (eh.gotError) {
        throw new RuntimeException("XSOM parser encountered error", eh.e);
    }
}
 
Example 17
Source File: UserParameterOpenHandler_2_3.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load the user parameters
 */
@Override
public void readUserParameters(InputStream inputStream)
    throws IOException, ParserConfigurationException, SAXException {

  logger.info("Loading user parameters");
  charBuffer = new StringBuffer();

  // Parse the XML file
  SAXParserFactory factory = SAXParserFactory.newInstance();
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(inputStream, this);

}
 
Example 18
Source File: TestSplitXml.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    factory = SAXParserFactory.newInstance();
    saxParser = factory.newSAXParser();
}
 
Example 19
Source File: XmlParser.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
public Element parse(InputStream stream) throws Exception {
	Document doc = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// xxe protection
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setXIncludeAware(false);
		factory.setExpandEntityReferences(false);

		factory.setNamespaceAware(true);
		if (policy == ValidationPolicy.EVERYTHING) {
			// use a slower parser that keeps location data
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer nullTransformer = transformerFactory.newTransformer();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			doc = docBuilder.newDocument();
			DOMResult domResult = new DOMResult(doc);
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			spf.setValidating(false);
			SAXParser saxParser = spf.newSAXParser();
			XMLReader xmlReader = saxParser.getXMLReader();
			// xxe protection
			spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
			spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
			xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

			XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
			InputSource inputSource = new InputSource(stream);
			SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
			nullTransformer.transform(saxSource, domResult);
		} else {
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(stream);
		}
	} catch (Exception e) {
		logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
		doc = null;
	}
	if (doc == null)
		return null;
	else
		return parse(doc);
}
 
Example 20
Source File: XmlUtil.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected SAXParserFactory initialValue() throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    return factory;
}