List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:ebay.dts.client.CreateLMSParser.java
/** * Create the SAX parser//from w w w .j a va 2 s .c om */ private void create() { try { // Obtain a new instance of a SAXParserFactory. SAXParserFactory factory = SAXParserFactory.newInstance(); // Specifies that the parser produced by this code will provide support for XML namespaces. factory.setNamespaceAware(true); // Specifies that the parser produced by this code will validate documents as they are parsed. factory.setValidating(true); // Creates a new instance of a SAXParser using the currently configured factory parameters. saxParser = factory.newSAXParser(); } catch (Throwable t) { t.printStackTrace(); } }
From source file:fedora.server.security.servletfilters.xmluserfile.ParserXmlUserfile.java
public ParserXmlUserfile(InputStream xmlStream) throws IOException { log.debug(this.getClass().getName() + ".init<> " + " begin"); m_xmlStream = xmlStream;//w ww . j av a 2 s. co m try { SAXParserFactory spf = SAXParserFactory.newInstance(); log.debug(this.getClass().getName() + ".init<> " + " after newInstance"); spf.setNamespaceAware(true); log.debug(this.getClass().getName() + ".init<> " + " after setNamespaceAware"); m_parser = spf.newSAXParser(); log.debug(this.getClass().getName() + ".init<> " + " after newSAXParser"); } catch (Exception e) { e.printStackTrace(); throw new IOException("Error getting XML parser: " + e.getMessage()); } catch (Throwable t) { log.fatal(this.getClass().getName() + ".init<> " + " caught me throwable"); t.printStackTrace(); log.fatal(this.getClass().getName() + ".populateCacheElement() " + t); log.fatal(this.getClass().getName() + ".populateCacheElement() " + t.getMessage() + " " + (t.getCause() == null ? "" : t.getCause().getMessage())); } }
From source file:Validate.java
void parse(String dir, String filename) throws FileNotFoundException, IOException, ParserConfigurationException, SAXException { try {/*from www . j av a 2 s .co m*/ File f = new File(dir, filename); StringBuffer errorBuff = new StringBuffer(); InputSource input = new InputSource(new FileInputStream(f)); // Set systemID so parser can find the dtd with a relative URL in the source document. input.setSystemId(f.toString()); SAXParserFactory spfact = SAXParserFactory.newInstance(); spfact.setValidating(true); spfact.setNamespaceAware(true); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //Instantiate inner-class error and lexical handler. Handler handler = new Handler(filename, errorBuff); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); parser.parse(input, handler); if (handler.containsDTD && !handler.errorOrWarning) // valid { buff.append("VALID " + filename + "\n"); numValidFiles++; } else if (handler.containsDTD) // not valid { buff.append("NOT VALID " + filename + "\n"); buff.append(errorBuff.toString()); numInvalidFiles++; } else // no DOCTYPE to use for validation { buff.append("NO DOCTYPE DECLARATION " + filename + "\n"); numFilesMissingDoctype++; } } catch (Exception e) // Serious problem! { buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n"); numMalformedFiles++; } finally { numXMLFiles++; } }
From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java
/** * Creates the xml source./*from w w w.ja v a 2s. co m*/ * * @param file the file * @return the source */ private Source createXMLSource(File file) { // disable validation in order to prevent url resolution of DTDs etc. SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); try { spf.setFeature("http://xml.org/sax/features/validation", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (Exception e) { logger.warn(e.getMessage()); } XMLReader reader; try { reader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { throw new IllegalStateException("Unable to create SAXParser", e); } return new SAXSource(reader, new InputSource(file.getAbsolutePath())); }
From source file:no.uis.service.studinfo.commons.StudinfoValidator.java
protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester, String language) throws Exception { // save xml//from w w w.j ava2 s .c o m File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml"); if (outFile.exists()) { outFile.delete(); } else { outFile.getParentFile().mkdirs(); } File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml"); Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET); backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE); backupWriter.flush(); backupWriter.close(); TransformerFactory trFactory = TransformerFactory.newInstance(); Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl")); Transformer stylesheet = trFactory.newTransformer(schemaSource); Source input = new StreamSource(new StringReader(studieinfoXml)); Result result = new StreamResult(outFile); stylesheet.transform(input, result); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = schemaFactory .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) }); factory.setSchema(schema); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language); reader.setErrorHandler(errorHandler); reader.setContentHandler(errorHandler); try { reader.parse( new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET))); } catch (SAXException ex) { // do nothing. The error is handled in the error handler } return errorHandler.getMessages(); }
From source file:com.zazuko.wikidata.municipalities.SparqlClient.java
List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException { CloseableHttpClient httpclient = HttpClients.createDefault(); URIBuilder builder = new URIBuilder(endpoint); builder.addParameter("query", query); HttpGet httpGet = new HttpGet(builder.build()); /*List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("query", query)); httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/ CloseableHttpResponse response2 = httpclient.execute(httpGet); try {// www . jav a2 s .c o m HttpEntity entity2 = response2.getEntity(); InputStream in = entity2.getContent(); if (debug) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int ch = in.read(); ch != -1; ch = in.read()) { System.out.print((char) ch); baos.write(ch); } in = new ByteArrayInputStream(baos.toByteArray()); } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler(); xmlReader.setContentHandler(sparqlsResultsHandler); xmlReader.parse(new InputSource(in)); /* for (int ch = in.read(); ch != -1; ch = in.read()) { System.out.print((char)ch); } */ // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); return sparqlsResultsHandler.getResults(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException ex) { throw new RuntimeException(ex); } finally { response2.close(); } }
From source file:com.google.code.docbook4j.renderer.BaseRenderer.java
protected SAXParserFactory createParserFactory() { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setXIncludeAware(true);/*from ww w . j av a2 s . c o m*/ factory.setNamespaceAware(true); return factory; }
From source file:net.sf.jabref.importer.fileformat.BibTeXMLImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it // creates// w w w .j a v a 2s .c om // parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object try { SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions BibTeXMLHandler handler = new BibTeXMLHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse(new InputSource(reader), handler); // When you're done, report the results stored by your handler object bibItems.addAll(handler.getItems()); } catch (javax.xml.parsers.ParserConfigurationException e) { LOGGER.error("Error with XML parser configuration", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (org.xml.sax.SAXException e) { LOGGER.error("Error during XML parsing", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (IOException e) { LOGGER.error("Error during file import", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:edu.psu.citeseerx.updates.external.metadata.ACMMetadataUpdater.java
public void updateACM() { try {/*w ww . java 2 s . com*/ // Get the SAX factory. SAXParserFactory factory = SAXParserFactory.newInstance(); // Neither we want validation nor namespaces. factory.setNamespaceAware(false); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); /*xmlReader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);*/ parser.parse(ACMDataFile, acmHandler); } catch (ParserConfigurationException e) { logger.error("The underlaying parser doesn't support the " + "requested feature", e); } catch (SAXException e) { logger.error("Error", e); } catch (IOException e) { logger.error("A parsing error has occurred: " + ACMDataFile, e); } }
From source file:com.ibm.jaql.lang.expr.xml.TypedXmlToJsonFn.java
@Override public JsonValue eval(Context context) throws Exception { if (parser == null) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser().getXMLReader(); handler = new TypedXmlToJsonHandler2(); parser.setContentHandler(handler); }/*from w w w . j av a2 s .com*/ JsonString s = (JsonString) exprs[0].eval(context); parser.parse(new InputSource(new StringReader(s.toString()))); return handler.result; }