List of usage examples for javax.xml.parsers DocumentBuilderFactory setCoalescing
public void setCoalescing(boolean coalescing)
From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java
/** * Creates the parser instance based on DOM parser factory, using the contents of a XML file. * Validation is not done. Return the documentElement of the XML document * /*w ww. j a v a2 s .c o m*/ * @param xmlFile - XML file to be parsed * @return documentElement of the XML file */ public static Document getXmlDocumentElement(String xmlFileContents) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Reader reader = new StringReader(xmlFileContents); InputSource inputSource = new InputSource(reader); factory.setCoalescing(true); factory.setNamespaceAware(false); factory.setIgnoringElementContentWhitespace(true); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(inputSource); }
From source file:AndroidUninstallStock.java
public static DocumentBuilderFactory getXmlDocFactory() throws SAXException { DocumentBuilderFactory xmlfactory = DocumentBuilderFactory.newInstance(); xmlfactory.setIgnoringComments(true); xmlfactory.setCoalescing(true); // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4867706 xmlfactory.setIgnoringElementContentWhitespace(true); xmlfactory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(AndroidUninstallStock.class.getResource("AndroidListSoft.xsd"))); xmlfactory.setValidating(false); // not DTD return xmlfactory; }
From source file:com.wudaosoft.net.httpclient.XmlResponseHandler.java
@Override public XmlObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { throw new ClientProtocolException("Unexpected response status: " + status); }//from ww w.ja v a 2s.co m HttpEntity entity = response.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); dbfac.setIgnoringElementContentWhitespace(true); dbfac.setCoalescing(true); dbfac.setIgnoringComments(true); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); // if (!contentType.equals(ContentType.APPLICATION_XML)) { // throw new ClientProtocolException("Unexpected content type:" + // contentType); // } Charset charset = contentType.getCharset(); if (charset == null) { charset = Consts.UTF_8; } return XmlObject.fromDocument(docBuilder.parse(entity.getContent(), charset.name())); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } }
From source file:net.sf.commons.ssh.directory.Directory.java
private Document getDocument(String resource) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setCoalescing(true); documentBuilderFactory.setIgnoringComments(true); documentBuilderFactory.setNamespaceAware(false); documentBuilderFactory.setValidating(false); final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(Directory.class.getResource(resource).toString()); }
From source file:edu.internet2.middleware.shibboleth.common.config.SpringDocumentLoader.java
/** {@inheritDoc} */ public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); factory.setCoalescing(true); factory.setIgnoringComments(true);/*from ww w . j a va 2s. c o m*/ factory.setNamespaceAware(true); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new LoggingErrorHandler(log)); builder.setEntityResolver(new ClasspathResolver()); return builder.parse(inputSource); }
From source file:at.tfr.securefs.module.validation.SchemaValidationModule.java
@Override public ModuleResult apply(InputStream input, ModuleConfiguration moduleConfiguration) throws ModuleException, IOException { SchemaResolver errorHandler = null;/* ww w. ja v a2 s . com*/ moduleStatistics.getCalls().incrementAndGet(); try { // parse an XML document into a DOM tree DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setCoalescing(true); dbf.setCoalescing(true); if (schema == null) { loadSchema(moduleConfiguration); } DOMImplementationLS domImpl = (DOMImplementationLS) dbf.newDocumentBuilder().getDOMImplementation(); errorHandler = new SchemaResolver(configuration.getSchemaPath(), domImpl); Validator validator = schema.newValidator(); validator.setErrorHandler(errorHandler); validator.setResourceResolver(errorHandler); validator.validate(new StreamSource(input)); } catch (SAXParseException e) { moduleStatistics.getFailures().incrementAndGet(); String message = "error validating: " + getCurrent() + " err: " + e; log.debug(message, e); log.info(message); if (moduleConfiguration.isMandatory()) { throw new ModuleException(message, e); } else { return new ModuleResult(false, e); } } catch (Exception e) { moduleStatistics.getErrors().incrementAndGet(); String message = "error validating: " + getCurrent() + " err: " + e; log.info(message, e); log.warn(message); if (moduleConfiguration.isMandatory()) { throw new IOException(message, e); } else { return new ModuleResult(false, e); } } if (errorHandler != null && errorHandler.getErrors().size() > 0) { moduleStatistics.getFailures().incrementAndGet(); String message = "Validation errors for File: " + getCurrent() + " errors: " + errorHandler.getErrors(); if (log.isDebugEnabled()) { log.debug(message); if (log.isTraceEnabled()) { log.trace("Validation warnings for File: " + getCurrent() + " errors: " + errorHandler.getWarnings()); } } if (moduleConfiguration.isMandatory()) { throw new ModuleException(message); } else { log.info("accepted errors - " + message); } return new ModuleResult(false, errorHandler.getErrors().get(0)); } moduleStatistics.getSuccesses().incrementAndGet(); return new ModuleResult(true); }
From source file:com.seajas.search.contender.service.modifier.ModifierScriptProcessor.java
/** * Default constructor./*from w w w .j av a 2 s . c o m*/ * * @throws ParserConfigurationException */ public ModifierScriptProcessor() throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setCoalescing(true); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); }
From source file:com.seajas.search.attender.service.template.TemplateService.java
/** * Create a results template result.// ww w. j a v a 2s. c o m * * @param language * @param queryString * @param query * @param uuid * @param searchResults * @return TemplateResult */ public TemplateResult createResults(final String language, final String queryString, final String query, final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults) throws ScriptException { Template template = templateDAO.findTemplate(TemplateType.Results, language); if (template == null) { logger.warn("Could not retrieve results template for language " + language + " - falling back to default language " + attenderService.getDefaultApplicationLanguage()); template = templateDAO.findTemplate(TemplateType.Confirmation, attenderService.getDefaultApplicationLanguage()); if (template == null) { logger.error("Could not retrieve fall-back results template for language " + attenderService.getDefaultApplicationLanguage() + " - not generating a template result"); return null; } } // Create an input document Document document; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setCoalescing(true); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); Element results = document.createElement("results"); results.setAttribute("templateLanguage", language); results.setAttribute("profileQuery", query); results.setAttribute("subscriberUUID", subscriberUUID); results.setAttribute("profileUUID", profileUUID); results.setAttribute("queryString", queryString); for (SearchResult searchResult : searchResults) results.appendChild(searchResult.toElement(document)); document.appendChild(results); // Plain text Transformer textTransformer = getTransformer(template, true); StringWriter textWriter = new StringWriter(); textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); textTransformer.transform(new DOMSource(document), new StreamResult(textWriter)); // HTML Transformer htmlTransformer = getTransformer(template, false); StringWriter htmlWriter = new StringWriter(); htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter)); return new TemplateResult(textWriter.toString(), htmlWriter.toString()); } catch (ScriptException e) { throw e; } catch (Exception e) { throw new ScriptException(e); } }
From source file:ws.argo.Responder.Responder.java
private ProbePayloadBean parseProbePayload(String payload) throws SAXException, IOException { ProbePayloadBean probePayload = new ProbePayloadBean(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setCoalescing(false); DocumentBuilder builder = null; try {/*w ww . ja v a 2 s. c om*/ builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } InputStream is = IOUtils.toInputStream(payload); Document document = builder.parse(is); Element probe = (Element) document.getElementsByTagName(PROBE).item(0); probePayload.probeID = probe.getAttribute("id"); probePayload.contractID = probe.getAttribute("contractID"); ArrayList<String> serviceContractIDs = new ArrayList<String>(); NodeList serviceContractNodes = probe.getElementsByTagName("serviceContractID"); probePayload.respondToURL = ((Element) probe.getElementsByTagName("respondTo").item(0)).getTextContent(); probePayload.respondToPayloadType = ((Element) probe.getElementsByTagName("respondToPayloadType").item(0)) .getTextContent(); for (int i = 0; i < serviceContractNodes.getLength(); i++) { Element serviceContractID = (Element) serviceContractNodes.item(i); String contractID = serviceContractID.getTextContent(); serviceContractIDs.add(contractID); } probePayload.serviceContractIDs = serviceContractIDs; return probePayload; }
From source file:com.mediaworx.xmlutils.XmlHelper.java
/** * Creates and returns a document builder that is configured with the following options: * <ul>/*from w w w. j a v a 2 s . c o m*/ * <li>don't validate</li> * <li>ignore comments</li> * <li>ignore content whitespace</li> * <li>convert CDATA nodes to text nodes</li> * <li>don't perform namespace processing</li> * <li>ignore DTDs</li> * </ul> * @return the DocumentBuilder * @throws ParserConfigurationException if for some reason the DocumentBuilder used to parse the XML can't be * initialized */ private DocumentBuilder getNonValidatingDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); documentBuilderFactory.setIgnoringComments(true); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilderFactory.setCoalescing(true); documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false); documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); return documentBuilderFactory.newDocumentBuilder(); }