List of usage examples for org.xml.sax XMLReader setFeature
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;
From source file:demo.SourceHttpMessageConverter.java
private SAXSource readSAXSource(InputStream body) throws IOException { try {/* w ww. j ava 2s . c o m*/ XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); reader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { reader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } byte[] bytes = StreamUtils.copyToByteArray(body); return new SAXSource(reader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex); } }
From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java
/** * reads a WSDL from input stream, modifies it and returns input stream to the result * @param wsdl//from ww w . j a va 2 s . c om * @return */ private InputStream modifyWsdl(InputStream wsdl) { try { TransformerHandler serializer = TRANSFORMER_FACTORY.newTransformerHandler(); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); serializer.setResult(result); OverwriteAttributeFilter filter = getModifyWsdlFilter(); filter.setContentHandler(serializer); XMLReader xmlreader = XMLReaderFactory.createXMLReader(); xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlreader.setProperty("http://xml.org/sax/properties/lexical-handler", new CommentsHandler(serializer)); xmlreader.setContentHandler(filter); // parse XML, filter it, put end result to a String xmlreader.parse(new InputSource(wsdl)); String resultString = writer.toString(); log.debug("result of WSDL cleanup: {}", resultString); // offer InputStream into processed String return new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); } catch (IOException | SAXException | TransformerConfigurationException e) { throw new RuntimeException(e); } }
From source file:com.sun.syndication.io.WireFeedInput.java
/** * Creates and sets up a org.jdom.input.SAXBuilder for parsing. * /*from w ww .j a v a2 s.c o m*/ * @return a new org.jdom.input.SAXBuilder object */ protected SAXBuilder createSAXBuilder() { SAXBuilder saxBuilder = new SAXBuilder(_validate); saxBuilder.setEntityResolver(RESOLVER); // // This code is needed to fix the security problem outlined in http://www.securityfocus.com/archive/1/297714 // // Unfortunately there isn't an easy way to check if an XML parser supports a particular feature, so // we need to set it and catch the exception if it fails. We also need to subclass the JDom SAXBuilder // class in order to get access to the underlying SAX parser - otherwise the features don't get set until // we are already building the document, by which time it's too late to fix the problem. // // Crimson is one parser which is known not to support these features. try { XMLReader parser = saxBuilder.createParser(); try { parser.setFeature("http://xml.org/sax/features/external-general-entities", false); saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { // ignore } try { parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); saxBuilder.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { // ignore } try { parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { // ignore } } catch (JDOMException e) { throw new IllegalStateException("JDOM could not create a SAX parser"); } saxBuilder.setExpandEntities(false); return saxBuilder; }
From source file:de.betterform.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *//*from www . j a v a 2s . c o m*/ public boolean validateSchema(Model model, Node instance) throws XFormsException { boolean valid = true; String message; if (LOGGER.isDebugEnabled()) LOGGER.debug("SchemaValidator.validateSchema: validating instance"); //needed if we want to load schemas from Model + set it as "schemaLocation" attribute String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema"); if (schemas != null && !schemas.equals("")) { // valid=false; //add schemas to element //shouldn't it be done on a copy of the doc ? Element el = null; if (instance.getNodeType() == Node.ELEMENT_NODE) el = (Element) instance; else if (instance.getNodeType() == Node.DOCUMENT_NODE) el = ((Document) instance).getDocumentElement(); else { if (LOGGER.isDebugEnabled()) LOGGER.debug("instance node type is: " + instance.getNodeType()); } String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); //test if with targetNamespace or not //if more than one schema : namespaces are mandatory ! (optional only for 1) StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false); String schemaLocations = null; String noNamespaceSchemaLocation = null; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); //check that it is an URL URI uri = null; try { uri = new java.net.URI(token); } catch (java.net.URISyntaxException ex) { if (LOGGER.isDebugEnabled()) LOGGER.debug(token + " is not an URI"); } if (uri != null) { String ns; try { ns = this.getSchemaNamespace(uri); if (ns != null && !ns.equals("")) { if (schemaLocations == null) schemaLocations = ns + " " + token; else schemaLocations = schemaLocations + " " + ns + " " + token; ///add the namespace declaration if it is not on the instance? //TODO: how to know with which prefix ? String nsPrefix = NamespaceResolver.getPrefix(el, ns); if (nsPrefix == null) { //namespace not declared ! LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token + " is not declared in instance: declaring it as default..."); el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns); } } else if (noNamespaceSchemaLocation == null) noNamespaceSchemaLocation = token; else { //we have more than one schema without namespace LOGGER.warn("SchemaValidator: There is more than one schema without namespace !"); } } catch (Exception ex) { LOGGER.warn( "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(), ex); //in case there was an exception: do nothing, do not set the schema } } } //write schemaLocations found if (schemaLocations != null && !schemaLocations.equals("")) el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation", noNamespaceSchemaLocation); //save and parse the doc ValidationErrorHandler handler = null; File f; try { //save document f = File.createTempFile("instance", ".xml"); f.deleteOnExit(); TransformerFactory trFact = TransformerFactory.newInstance(); Transformer trans = trFact.newTransformer(); DOMSource source = new DOMSource(el); StreamResult result = new StreamResult(f); trans.transform(source, result); if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath()); //parse it with error handler to validate it handler = new ValidationErrorHandler(); SAXParserFactory parserFact = SAXParserFactory.newInstance(); parserFact.setValidating(true); parserFact.setNamespaceAware(true); SAXParser parser = parserFact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //validation activated reader.setFeature("http://xml.org/sax/features/validation", true); //schema validation activated reader.setFeature("http://apache.org/xml/features/validation/schema", true); //used only to validate the schema, not the instance //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); //validate only if there is a grammar reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); parser.parse(f, handler); } catch (Exception ex) { LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex); //throw new XFormsException("XMLSchema validation failed. "+message); } //if no exception if (handler != null && handler.isValid()) valid = true; else { message = handler.getMessage(); //TODO: find a way to get the error message displayed throw new XFormsException("XMLSchema validation failed. " + message); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: result=" + valid); } return valid; }
From source file:org.semantictools.frame.api.OntologyManager.java
private void loadXsd(File file) throws SchemaParseException { try {/*from ww w .j a v a2 s . c o m*/ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setFeature("http://xml.org/sax/features/namespaces", true); NamespaceReader handler = new NamespaceReader(); reader.setContentHandler(handler); parser.parse(file, handler); String namespace = handler.getTargetNamespace(); if (namespace == null) { logger.warn("Ignoring schema since targetNamespace is not declared: " + file.getPath()); } else { OntologyEntity entity = new OntologyEntity(XML_FORMAT, file, namespace); uri2OntologyEntity.put(namespace, entity); } } catch (Throwable oops) { throw new SchemaParseException(oops); } }
From source file:de.suse.swamp.core.util.BugzillaTools.java
private synchronized void xmlToData(String url) throws Exception { HttpState initialState = new HttpState(); String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME"); String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD"); if (authUsername != null && authUsername.length() != 0) { Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword); initialState.setCredentials(AuthScope.ANY, defaultcreds); } else {/* w w w . j ava 2 s. com*/ Cookie[] cookies = getCookies(); for (int i = 0; i < cookies.length; i++) { initialState.addCookie(cookies[i]); Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log); } } HttpClient httpclient = new HttpClient(); httpclient.setState(initialState); HttpMethod httpget = new GetMethod(url); try { httpclient.executeMethod(httpget); } catch (Exception e) { throw new Exception("Could not get URL " + url); } String content = httpget.getResponseBodyAsString(); char[] chars = content.toCharArray(); // removing illegal characters from bugzilla output. for (int i = 0; i < chars.length; i++) { if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) { Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log); chars[i] = ' '; } } Logger.DEBUG(String.valueOf(chars), log); CharArrayReader reader = new CharArrayReader(chars); XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); parser.setFeature("http://xml.org/sax/features/validation", false); // disable parsing of external dtd parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); // get XML File BugzillaReader handler = new BugzillaReader(); parser.setContentHandler(handler); InputSource source = new InputSource(); source.setCharacterStream(reader); source.setEncoding("utf-8"); try { parser.parse(source); } catch (SAXParseException spe) { spe.printStackTrace(); throw spe; } httpget.releaseConnection(); if (errormsg != null) { throw new Exception(errormsg); } }
From source file:com.mirth.connect.model.converters.NCPDPSerializer.java
@Override public String fromXML(String source) throws SerializerException { /*/*from ww w . j ava 2 s . c o m*/ * Need to determine the version by looking at the raw message. * The transaction header will contain the version ("51" for 5.1 and * "D0" for D.0) */ String version = "D0"; if (source.indexOf("D0") == -1) { version = "51"; } else if (source.indexOf("51") == -1) { version = "D0"; } else if (source.indexOf("51") < source.indexOf("D0")) { version = "51"; } try { XMLReader reader = XMLReaderFactory.createXMLReader(); NCPDPXMLHandler handler = new NCPDPXMLHandler(segmentDelimeter, groupDelimeter, fieldDelimeter, version); reader.setContentHandler(handler); if (useStrictValidation) { reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "ncpdp" + version + ".xsd"); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp" + version + ".xsd"); } /* * Parse, but first replace all spaces between brackets. This fixes * pretty-printed XML we might receive */ reader.parse(new InputSource(new StringReader(source.replaceAll(">\\s+<", "><")))); return handler.getOutput().toString(); } catch (Exception e) { throw new SerializerException("Error converting XML to NCPDP message.", e); } }
From source file:eionet.cr.util.xml.XmlAnalysis.java
/** * * @param inputStream/*w w w. ja va2 s . co m*/ * @return * @throws SAXException * @throws ParserConfigurationException * @throws GDEMException * @throws SAXException * @throws IOException */ public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { // set up the parser and reader SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // turn off validation against schema or dtd (we only need the document to be well-formed XML) parserFactory.setValidating(false); reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://apache.org/xml/features/validation/schema", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/namespaces", true); // turn on dtd handling doctypeReader = new SAXDoctypeReader(); try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader); } catch (SAXNotRecognizedException e) { logger.warn("Installed XML parser does not provide lexical events", e); } catch (SAXNotSupportedException e) { logger.warn("Cannot turn on comment processing here", e); } // set the handler and do the parsing handler = new Handler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(inputStream)); } catch (SAXException e) { Exception ee = e.getException(); if (ee == null || !(ee instanceof CRException)) throw e; } }
From source file:com.thruzero.common.core.infonode.builder.SaxInfoNodeBuilder.java
/** construct complete {@code InfoNodeElement} from dom. */ protected InfoNodeElement doBuildInfoNode(final String xml, final InfoNodeElement targetNode, final InfoNodeFilterChain infoNodeFilterChain) throws Exception { handlePrimaryKey(targetNode);/* w w w .java 2 s . c o m*/ if (StringUtils.isNotEmpty(xml)) { XMLReader parser = XMLReaderFactory.createXMLReader(); InfoNodeSaxHandler dnHandler = new InfoNodeSaxHandler(targetNode, infoNodeFilterChain); // state for this build is kept in this InfoNode Handler instance parser.setContentHandler(dnHandler); parser.setErrorHandler(dnHandler); parser.setFeature("http://xml.org/sax/features/validation", false); InputSource input = new InputSource(new StringReader(xml)); parser.parse(input); } handleRootNode(targetNode); return targetNode; }
From source file:Examples.java
/** * Show the Transformer as a simple XMLFilter. This is pretty similar * to exampleXMLReader, except that here the parent XMLReader is created * by the caller, instead of automatically within the XMLFilter. This * gives the caller more direct control over the parent reader. *///from w w w. j ava 2s. co m public static void exampleXMLFilter(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException // , ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); 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(); // The transformer will use a SAX parser as it's reader. reader.setContentHandler(new ExampleContentHandler()); try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (SAXException se) { // What can we do? // TODO: User diagnostics. } XMLFilter filter = ((SAXTransformerFactory) tfactory).newXMLFilter(new StreamSource(xslID)); filter.setParent(reader); // Now, when you call transformer.parse, it will set itself as // the content handler for the parser object (it's "parent"), and // will then call the parse method on the parser. filter.parse(new InputSource(sourceID)); }