List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java
protected URL[] readIndex(MavenProject project) throws MavenReportException { try {//from www . j av a 2 s . c om // 1. read master faces-config.xml resources List masters = getMasterConfigs(project); if (masters.isEmpty()) { getLog().warn("Master faces-config.xml not found"); return new URL[0]; } else { List entries = new LinkedList(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); // requires JAXP 1.3, in JavaSE 5.0 // spf.setXIncludeAware(false); for (Iterator<URL> i = masters.iterator(); i.hasNext();) { URL url = i.next(); Digester digester = new Digester(spf.newSAXParser()); digester.setNamespaceAware(true); // XInclude digester.setRuleNamespaceURI(XIncludeFilter.XINCLUDE_NAMESPACE); digester.addCallMethod("faces-config/include", "add", 1); digester.addFactoryCreate("faces-config/include", URLCreationFactory.class); digester.addCallParam("faces-config/include", 0, 0); digester.push(url); digester.push(entries); digester.parse(url.openStream()); } return (URL[]) entries.toArray(new URL[0]); } } catch (ParserConfigurationException e) { throw new MavenReportException("Failed to parse master config", e); } catch (SAXException e) { throw new MavenReportException("Failed to parse master config", e); } catch (IOException e) { throw new MavenReportException("Failed to parse master config", e); } }
From source file:org.apache.oozie.util.GraphGenerator.java
/** * Stream the PNG file to client// w w w .ja v a 2s .co m * @param out * @throws Exception */ public void write(OutputStream out) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new XMLParser(out)); xmlReader.parse(new InputSource(new StringReader(xml))); }
From source file:org.apache.openmeetings.db.dao.label.LabelDao.java
private static List<StringLabel> getLabels(InputStream is) throws Exception { final List<StringLabel> labels = new ArrayList<StringLabel>(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); try {/*from w w w . ja v a2 s .c o m*/ SAXParser parser = spf.newSAXParser(); XMLReader xr = parser.getXMLReader(); xr.setContentHandler(new ContentHandler() { StringLabel label = null; @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (ENTRY_ELEMENT.equals(localName)) { label = new StringLabel(atts.getValue(KEY_ATTR), ""); } } @Override public void startDocument() throws SAXException { } @Override public void skippedEntity(String name) throws SAXException { } @Override public void setDocumentLocator(Locator locator) { } @Override public void processingInstruction(String target, String data) throws SAXException { } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } @Override public void endPrefixMapping(String prefix) throws SAXException { } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (ENTRY_ELEMENT.equals(localName)) { labels.add(label); } } @Override public void endDocument() throws SAXException { } @Override public void characters(char[] ch, int start, int length) throws SAXException { StringBuilder sb = new StringBuilder(label.getValue()); sb.append(ch, start, length); label.setValue(sb.toString()); } }); xr.parse(new InputSource(is)); } catch (Exception e) { throw e; } return labels; }
From source file:org.apache.shindig.social.opensocial.util.XSDValidator.java
/** * Validate a xml input stream against a supplied schema. * * @param xml//from w ww .j a v a 2s .co m * a stream containing the xml * @param schema * a stream containing the schema * @return a list of errors or warnings, a 0 lenght string if none. */ public static String validate(InputStream xml, InputStream schema) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); final StringBuilder errors = new StringBuilder(); try { SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA); Schema s = schemaFactory.newSchema(new StreamSource(schema)); Validator validator = s.newValidator(); final LSResourceResolver lsr = validator.getResourceResolver(); validator.setResourceResolver(new LSResourceResolver() { public LSInput resolveResource(String arg0, String arg1, String arg2, String arg3, String arg4) { log.info("resolveResource(" + arg0 + ',' + arg1 + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')'); return lsr.resolveResource(arg0, arg1, arg2, arg3, arg4); } }); validator.validate(new StreamSource(xml)); } catch (IOException e) { } catch (SAXException e) { errors.append(e.getMessage()).append('\n'); } return errors.toString(); }
From source file:org.apache.synapse.mediators.builtin.ValidateMediator.java
public boolean mediate(SynapseContext synCtx) { ByteArrayInputStream baisFromSource = null; StringBuffer nsLocations = new StringBuffer(); try {/* w w w. j a v a 2 s .c o m*/ // create a byte array output stream and serialize the source node into it ByteArrayOutputStream baosForSource = new ByteArrayOutputStream(); XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource); // save the list of defined namespaces for validation against the schema OMNode sourceNode = getValidateSource(synCtx.getSynapseMessage()); if (sourceNode instanceof OMElement) { Iterator iter = ((OMElement) sourceNode).getAllDeclaredNamespaces(); while (iter.hasNext()) { OMNamespace omNS = (OMNamespace) iter.next(); nsLocations.append(omNS.getName() + " " + getSchemaUrl()); } } sourceNode.serialize(xsWriterForSource); baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray()); } catch (Exception e) { String msg = "Error accessing source element for validation : " + source; log.error(msg); throw new SynapseException(msg, e); } try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); spFactory.setNamespaceAware(true); spFactory.setValidating(true); SAXParser parser = spFactory.newSAXParser(); parser.setProperty(VALIDATION, Boolean.TRUE); parser.setProperty(SCHEMA_VALIDATION, Boolean.TRUE); parser.setProperty(FULL_CHECKING, Boolean.TRUE); parser.setProperty(SCHEMA_LOCATION_NS, nsLocations.toString()); parser.setProperty(SCHEMA_LOCATION_NO_NS, getSchemaUrl()); Validator handler = new Validator(); parser.parse(baisFromSource, handler); if (handler.isValidationError()) { log.debug("Validation failed :" + handler.getSaxParseException().getMessage()); // super.mediate() invokes the "on-fail" sequence of mediators return super.mediate(synCtx); } } catch (Exception e) { String msg = "Error validating " + source + " against schema : " + schemaUrl + " : " + e.getMessage(); log.error(msg); throw new SynapseException(msg, e); } return true; }
From source file:org.apache.tapestry.util.xml.RuleDirectedParser.java
/** * Configures a {@link SAXParserFactory} before * {@link SAXParserFactory#newSAXParser()} is invoked. * The default implementation sets validating to true * and namespaceAware to false,// w w w . j ava 2 s. c om */ protected void configureParserFactory(SAXParserFactory factory) { factory.setValidating(true); factory.setNamespaceAware(false); }
From source file:org.atombeat.xquery.functions.util.RequestGetData.java
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI); // request object is read from global variable $request Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR); if (var == null || var.getValue() == null) throw new XPathException(this, "No request object found in the current XQuery context."); if (var.getValue().getItemType() != Type.JAVA_OBJECT) throw new XPathException(this, "Variable $request is not bound to an Java object."); JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0); if (value.getObject() instanceof RequestWrapper) { RequestWrapper request = (RequestWrapper) value.getObject(); //if the content length is unknown, return if (request.getContentLength() == -1) { return Sequence.EMPTY_SEQUENCE; }/* ww w. ja v a 2 s .c om*/ //first, get the content of the request byte[] bufRequestData = null; try { InputStream is = request.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(request.getContentLength()); byte[] buf = new byte[256]; int l = 0; while ((l = is.read(buf)) > -1) { bos.write(buf, 0, l); } bufRequestData = bos.toByteArray(); } catch (IOException ioe) { throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe); } //was there any POST content if (bufRequestData != null) { //determine if exists mime database considers this binary data String contentType = request.getContentType(); if (contentType != null) { //strip off any charset encoding info if (contentType.indexOf(";") > -1) contentType = contentType.substring(0, contentType.indexOf(";")); MimeType mimeType = MimeTable.getInstance().getContentType(contentType); //<atombeat> // this code will only encode the request data if the mimeType // is present in the mime table, and the mimeType is stated // as binary... // if(mimeType != null) // { // if(!mimeType.isXMLType()) // { // //binary data // return new Base64Binary(bufRequestData); // } // } // this code takes a more conservative position and assumes that // if the mime type is not present in the table, the request // data should be treated as binary, and should be encoded as // base 64... if (mimeType == null || !mimeType.isXMLType()) { return new Base64Binary(bufRequestData); } //</atombeat> } //try and parse as an XML documemnt, otherwise fallback to returning the data as a string context.pushDocumentContext(); try { //try and construct xml document from input stream, we use eXist's in-memory DOM implementation SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //TODO : we should be able to cope with context.getBaseURI() InputSource src = new InputSource(new ByteArrayInputStream(bufRequestData)); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true); reader.setContentHandler(receiver); reader.parse(src); Document doc = receiver.getDocument(); return (NodeValue) doc.getDocumentElement(); } catch (ParserConfigurationException e) { //do nothing, we will default to trying to return a string below } catch (SAXException e) { //do nothing, we will default to trying to return a string below } catch (IOException e) { //do nothing, we will default to trying to return a string below } finally { context.popDocumentContext(); } //not a valid XML document, return a string representation of the document String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } try { String s = new String(bufRequestData, encoding); return new StringValue(s); } catch (IOException e) { throw new XPathException(this, "An IO exception ocurred: " + e.getMessage(), e); } } else { //no post data return Sequence.EMPTY_SEQUENCE; } } else { throw new XPathException(this, "Variable $request is not bound to a Request object."); } }
From source file:org.chiba.xml.xforms.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *///www. ja v a 2s .co 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, 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(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(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.codehaus.enunciate.config.EnunciateConfiguration.java
/** * Create the digester.// w ww . j ava 2 s . co m * * @return The digester that was created. */ protected Digester createDigester() throws SAXException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); Properties properties = new Properties(); properties.put("SAXParserFactory", factory); // properties.put("schemaLocation", EnunciateConfiguration.class.getResource("enunciate.xsd").toString()); // properties.put("schemaLanguage", "http://www.w3.org/2001/XMLSchema"); SAXParser parser = GenericParser.newSAXParser(properties); return new Digester(parser); } catch (ParserConfigurationException e) { throw new SAXException(e); } }
From source file:org.codehaus.enunciate.modules.xml.XMLDeploymentModule.java
/** * Pretty-prints the specified xml file. * * @param file The file to pretty-print. *///from w w w .ja v a2 s . co m protected void prettyPrint(File file) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); File prettyFile = enunciate.createTempFile("enunciate", file.getName()); parser.parse(file, new PrettyPrinter(prettyFile)); if (file.delete()) { enunciate.copyFile(prettyFile, file); } else { warn("Unable to delete %s. Skipping pretty-print transformation....", file); } } catch (Exception e) { //fall through... skip pretty printing. warn("Unable to pretty-print %s (%s).", file, e.getMessage()); if (enunciate.isDebug()) { e.printStackTrace(System.err); } } }