List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:Examples.java
/** * This example shows how to chain events from one Transformer * to another transformer, using the Transformer as a * SAX2 XMLFilter/XMLReader./*from ww w. j a v a 2s. co m*/ */ public static void exampleXMLFilterChain(String sourceID, String xslID_1, String xslID_2, String xslID_3) throws TransformerException, TransformerConfigurationException, SAXException, IOException { TransformerFactory tfactory = TransformerFactory.newInstance(); Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1)); Transformer transformer1 = stylesheet1.newTransformer(); // If one success, assume all will succeed. if (tfactory.getFeature(SAXSource.FEATURE)) { SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1)); XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2)); XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3)); if (null != filter1) // If one success, assume all were success. { // transformer1 will use a SAX parser as it's reader. filter1.setParent(reader); // transformer2 will use transformer1 as it's reader. filter2.setParent(filter1); // transform3 will use transform2 as it's reader. filter3.setParent(filter2); filter3.setContentHandler(new ExampleContentHandler()); // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler()); // Now, when you call transformer3 to parse, it will set // itself as the ContentHandler for transform2, and // call transform2.parse, which will set itself as the // content handler for transform1, and call transform1.parse, // which will set itself as the content listener for the // SAX parser, and call parser.parse(new InputSource("xml/foo.xml")). filter3.parse(new InputSource(sourceID)); } else { System.out.println("Can't do exampleXMLFilter because " + "tfactory doesn't support asXMLFilter()"); } } else { System.out.println("Can't do exampleXMLFilter because " + "tfactory is not a SAXTransformerFactory"); } }
From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java
public static SAXParser getSaxParser() { if (!SAX_PARSER_ERROR) { try {//from www .ja v a 2 s . c o m SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); return parser; } catch (Exception e) { StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory. Switching to OSGI service reference.")); SAX_PARSER_ERROR = true; } } BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext(); ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName()); if (reference != null) { try { synchronized (SAX_PARSER_LOCK) { SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference); return factory.newSAXParser(); } } catch (Exception e) { StatusHandler .log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e)); } finally { bundleContext.ungetService(reference); } } return null; }
From source file:Main.java
public void process() { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true);/*from w w w .j a v a 2 s . co m*/ System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware"); System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML"); try { parser = spf.newSAXParser(); System.out.println("Parser object is: " + parser); } catch (SAXException e) { e.printStackTrace(System.err); System.exit(1); } catch (ParserConfigurationException e) { e.printStackTrace(System.err); System.exit(1); } try { parser.parse(new InputSource(new StringReader(getXMLData())), this); } catch (IOException e) { e.printStackTrace(System.err); } catch (SAXException e) { e.printStackTrace(System.err); } }
From source file:TrySAX.java
private void process(File file) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true);/* w ww. j a v a2 s . c o m*/ System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware"); System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML"); try { parser = spf.newSAXParser(); System.out.println("Parser object is: " + parser); } catch (SAXException e) { e.printStackTrace(System.err); System.exit(1); } catch (ParserConfigurationException e) { e.printStackTrace(System.err); System.exit(1); } System.out.println("\nStarting parsing of " + file + "\n"); try { parser.parse(file, this); } catch (IOException e) { e.printStackTrace(System.err); } catch (SAXException e) { e.printStackTrace(System.err); } }
From source file:org.energyos.espi.datacustodian.integration.utils.ATOMContentHandlerTests.java
@Test @Ignore//from w ww.j av a2s . com public void processEnty() throws Exception { JAXBContext context = marshaller.getJaxbContext(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); // EntryProcessorServiceImpl procssor = // mock(EntryProcessorServiceImpl.class); ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService); reader.setContentHandler(atomContentHandler); reader.parse(new InputSource(FixtureFactory.newUsagePointInputStream(UUID.randomUUID()))); // verify(procssor).process(any(EntryType.class)); }
From source file:ValidateXMLInput.java
void validate() throws Exception { // Since we're going to use a SAX feature, the transformer must support // input in the form of a SAXSource. TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(SAXSource.FEATURE)) { // Standard way of creating an XMLReader in JAXP 1.1. SAXParserFactory pfactory = SAXParserFactory.newInstance(); pfactory.setNamespaceAware(true); // Very important! // Turn on validation. pfactory.setValidating(true);/*ww w . j a va 2 s .co m*/ // Get an XMLReader. XMLReader reader = pfactory.newSAXParser().getXMLReader(); // Instantiate an error handler (see the Handler inner class below) that will report any // errors or warnings that occur as the XMLReader is parsing the XML input. Handler handler = new Handler(); reader.setErrorHandler(handler); // Standard way of creating a transformer from a URL. Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl")); // Specify a SAXSource that takes both an XMLReader and a URL. SAXSource source = new SAXSource(reader, new InputSource("birds.xml")); // Transform to a file. try { t.transform(source, new StreamResult("birds.out")); } catch (TransformerException te) { // The TransformerException wraps someting other than a SAXParseException // warning or error, either of which should be "caught" by the Handler. System.out.println("Not a SAXParseException warning or error: " + te.getMessage()); } System.out.println("=====Done====="); } else System.out.println("tfactory does not support SAX features!"); }
From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java
@SneakyThrows private static SAXParserFactory createSaxParserFactory() { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); // disable external entity parsing to avoid DOS attacks factory.setValidating(false);/*from ww w . j a va 2 s. c o m*/ 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); return factory; }
From source file:ddf.compression.exi.EXIEncoderTest.java
/** * Tests that the encode method converts xml into exi-compressed xml. * * @throws Exception/*from www.j av a 2s . c o m*/ */ @Test public void testEncode() throws Exception { ByteArrayOutputStream exiStream = new ByteArrayOutputStream(); InputStream xmlStream = getClass().getResourceAsStream(TEST_FILE); EXIEncoder.encode(xmlStream, exiStream); StringWriter stringWriter = new StringWriter(); GrammarCache grammarCache; SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler(); EXIReader reader = new EXIReader(); grammarCache = new GrammarCache(null, GrammarOptions.DEFAULT_OPTIONS); reader.setGrammarCache(grammarCache); transformerHandler.setResult(new StreamResult(stringWriter)); reader.setContentHandler(transformerHandler); reader.parse(new InputSource(new ByteArrayInputStream(exiStream.toByteArray()))); XMLUnit.setNormalize(true); XMLUnit.setNormalizeWhitespace(true); InputStream stream = getClass().getResourceAsStream(TEST_FILE); Diff diff = XMLUnit.compareXML(IOUtils.toString(stream), stringWriter.getBuffer().toString()); IOUtils.closeQuietly(stream); assertTrue("The XML input file (" + TEST_FILE + ") did not match the EXI-decoded output", diff.similar()); }
From source file:joachimeichborn.geotag.io.parser.gpx.GpxParser.java
public joachimeichborn.geotag.model.Track read(final Path aGpxFile) throws IOException { logger.fine("Reading positions from " + aGpxFile); final List<PositionData> positions = new LinkedList<>(); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); try {//from w w w . jav a2s .com final SAXParser saxParser = factory.newSAXParser(); final Handler handler = new Handler(); saxParser.parse(aGpxFile.toFile(), handler); positions.addAll(handler.getPositions()); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } logger.fine("Read " + positions.size() + " coordinates from " + aGpxFile); return new joachimeichborn.geotag.model.Track(aGpxFile, positions); }
From source file:com.eventestimator.mvc.ContactCollectionController.java
@RequestMapping(value = "/json.j", method = RequestMethod.GET) protected ResponseEntity<Object> getContacts(Model model, HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String userName = (String) session.getAttribute("userName"); String accessToken = (String) session.getAttribute("accessToken"); String contactUrl = WS_URL_PREFIX + userName + "/contacts?access_token=" + accessToken; Feed contactSource = restTemplate.getForObject(contactUrl, Feed.class); List<Entry> contacts = contactSource.getEntries(); List<Contact> contactObjects = new ArrayList<Contact>(contacts.size()); for (Entry contact : contacts) { Link link = (Link) contact.getOtherLinks().get(0); String linkHref = link.getHref(); String contentXML = restTemplate.getForObject(WS_DOMAIN + linkHref + "?access_token=" + accessToken, String.class); // List<Content> contactContents = contactEntry.getBody().getContents(); // List<Content> contactContents = contactEntry.getContents(); ///*from ww w. ja va2 s .c o m*/ // Content contactContent = contactContents.get(0); // String contentXML = contactContent.getValue(); final SAXParserFactory sax = SAXParserFactory.newInstance(); sax.setNamespaceAware(false); final XMLReader reader; try { reader = sax.newSAXParser().getXMLReader(); } catch (SAXException e) { throw new RuntimeException(e); } InputSource is = new InputSource(new StringReader(contentXML)); SAXSource source = new SAXSource(reader, is); JAXBContext context = JAXBContext.newInstance(ContactEntry.class); javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller(); JAXBElement<ContactEntry> contactEntry = (JAXBElement<ContactEntry>) unmarshaller.unmarshal(source, ContactEntry.class); Contact contactObject = contactEntry.getValue().getContent().getContact(); contactObjects.add(contactObject); } ResponseEntity<Object> response = new ResponseEntity<Object>(contactObjects, HttpStatus.OK); return response; }