List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating
public void setValidating(boolean validating)
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public String getLanguagesFromCS() { String listOfLangs = ""; try {/*from ww w . ja v a 2s.co m*/ ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("content/language/languages.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(url.getFile()); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("entry"); String seperator = ""; for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (listOfLangs.length() > 1) { seperator = ","; } Element link = (Element) nodeLst.item(s); String a1 = link.getAttribute("key"); if (getCountryIdsFromCS(a1).get(0) != null) { listOfLangs = listOfLangs + seperator + a1; } } } catch (Exception e) { Log.error(e.getMessage()); } return listOfLangs; }
From source file:i5.las2peer.services.mobsos.surveys.SurveyService.java
/** * Initialize XML parser and validator for questionnaire forms and answers * // w ww . j ava2 s . c o m * @throws SAXException * @throws ParserConfigurationException */ private void initXMLInfrastructure() throws SAXException, ParserConfigurationException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(questionnaireSchemaPath)); validator = schema.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setSchema(schema); dbf.setNamespaceAware(true); dbf.setValidating(false); parser = dbf.newDocumentBuilder(); }
From source file:com.dosse.bwentrain.androidPlayer.MainActivity.java
private Preset loadPreset(String f) { InputStream p = null;/* w ww .j a v a 2s.c o m*/ Preset x = null; try { if (new File(f).exists()) p = new FileInputStream(f); else p = openFileInput(f); if (p == null) throw new Exception("Can't open " + f); //read xml document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(p); doc.getDocumentElement().normalize(); //parse it x = new Preset(doc.getDocumentElement()); if (getSharedPreferences("SINE", Context.MODE_PRIVATE).getBoolean("noise_switch", false)) { //if noise is disabled, remove it Envelope e = x.getNoiseEnvelope(); while (e.getPointCount() != 1) e.removePoint(1); e.setVal(0, 0); } } catch (Throwable t) { //corrupt or not a preset file Log.e("SINE", f + " invalid because " + t.toString()); } finally { if (p != null) try { p.close(); } catch (IOException e) { } } return x; }
From source file:net.sourceforge.pmd.lang.xml.ast.XmlParser.java
protected Document parseDocument(Reader reader) throws ParseException { nodeCache.clear();/* w w w. j a va 2s.c o m*/ try { String xmlData = IOUtils.toString(reader); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(parserOptions.isNamespaceAware()); dbf.setValidating(parserOptions.isValidating()); dbf.setIgnoringComments(parserOptions.isIgnoringComments()); dbf.setIgnoringElementContentWhitespace(parserOptions.isIgnoringElementContentWhitespace()); dbf.setExpandEntityReferences(parserOptions.isExpandEntityReferences()); dbf.setCoalescing(parserOptions.isCoalescing()); dbf.setXIncludeAware(parserOptions.isXincludeAware()); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); documentBuilder.setEntityResolver(parserOptions.getEntityResolver()); Document document = documentBuilder.parse(new InputSource(new StringReader(xmlData))); DOMLineNumbers lineNumbers = new DOMLineNumbers(document, xmlData); lineNumbers.determine(); return document; } catch (ParserConfigurationException | SAXException | IOException e) { throw new ParseException(e); } }
From source file:nl.armatiek.xslweb.utils.XMLUtils.java
public static DocumentBuilder getDocumentBuilder(boolean validate, boolean namespaceAware, boolean xincludeAware) throws XSLWebException { try {//w w w .ja va 2s. c om DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); if (xincludeAware) { docFactory.setFeature("http://apache.org/xml/features/xinclude", true); docFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); docFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-language", false); docFactory.setXIncludeAware(true); } docFactory.setNamespaceAware(namespaceAware); docFactory.setValidating(validate); docFactory.setExpandEntityReferences(true); if (validate) { docFactory.setFeature("http://apache.org/xml/features/validation/dynamic", true); docFactory.setFeature("http://apache.org/xml/features/validation/schema", true); } docFactory.setIgnoringElementContentWhitespace(true); return docFactory.newDocumentBuilder(); } catch (Exception e) { throw new XSLWebException(e); } }
From source file:nl.b3p.kaartenbalie.service.requesthandler.GetCapabilitiesRequestHandler.java
/** * Processes the parameters and creates a DocumentBuilder from the given * parameters. This DocumentBuilder will be used to create a XML based * String which can be returned to the client. * * @param dw DataWrapper which contains all information that has to be sent * to the client/* w w w. j a v a2 s. c o m*/ * @param user User the user which invoked the request * * @return byte[] * * @throws Exception * @throws IOException */ // <editor-fold defaultstate="" desc="getRequest(DataWrapper dw, User user) method."> public void getRequest(DataWrapper dw, User user) throws IOException, Exception { dw.setHeader("Content-Disposition", "inline; filename=\"GetCapabilities.xml\";"); dw.setContentType(OGCConstants.WMS_PARAM_WMS_XML); String spAbbrUrl = dw.getOgcrequest().getServiceProviderName(); ByteArrayOutputStream output = null; if (user != null) { this.user = user; this.url = user.getPersonalURL(dw.getRequest(), spAbbrUrl); } if (url == null) { throw new Exception("No personal url for user found."); } /* * Only used if specific param is given (used for configuration) */ boolean isAdmin = false; if ("true".equalsIgnoreCase(dw.getOgcrequest().getParameter("_VIEWER_CONFIG"))) { Set userRoles = user.getRoles(); Iterator rolIt = userRoles.iterator(); while (rolIt.hasNext()) { Roles role = (Roles) rolIt.next(); if (role.getRole().equalsIgnoreCase(Roles.ADMIN)) { /* de gebruiker is een beheerder */ isAdmin = true; break; } } } /* * Only used if specific param is given (used for monitoring) */ if ("true".equalsIgnoreCase(dw.getOgcrequest().getParameter("_FORCE_FETCH"))) { forceFetch(dw, isAdmin); } ServiceProvider s = getServiceProvider(isAdmin, spAbbrUrl); if (user != null) { s.setOrganizationCode(user.getOrganisationCodes()); s.setExpireDate(user.getTimeout()); s.setUserName(user.getName()); s.setGivenName(user.getFirstName() + " " + user.getSurname()); s.setPersonalCode(user.getPersonalURL()); } HashMap conversionValues = new HashMap(); conversionValues.put("url", url); s.convertValues2KB(conversionValues); /* * Create a DocumentBuilderFactory from which a new document can be created */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); DOMImplementation di = db.getDOMImplementation(); // <!DOCTYPE WMT_MS_Capabilities SYSTEM "http://schemas.opengeospatial.net/wms/1.1.1/WMS_MS_Capabilities.dtd" // [ // <!ELEMENT VendorSpecificCapabilities EMPTY> // ]> <!-- end of DOCTYPE declaration --> DocumentType dt = di.createDocumentType("WMT_MS_Capabilities", null, CallWMSServlet.CAPABILITIES_DTD); Document dom = di.createDocument(null, "WMT_MS_Capabilities", dt); Element rootElement = dom.getDocumentElement(); rootElement = s.toElement(dom, rootElement); rootElement.setAttribute("version", "1.1.1"); /* * Create a new output format to which this document should be translated and * serialize the tree to an XML document type */ OutputFormat format = new OutputFormat(dom, KBConfiguration.CHARSET, true); format.setIndenting(true); output = new ByteArrayOutputStream(); XMLSerializer serializer = new XMLSerializer(output, format); serializer.serialize(dom); DOMValidator dv = new DOMValidator(); dv.parseAndValidate(new ByteArrayInputStream(output.toString().getBytes(KBConfiguration.CHARSET))); dw.write(output); }
From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java
private void handleRequestExceptionAsXML(Exception ex, DataWrapper data) throws IOException { ByteArrayOutputStream output = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true);// w w w. j av a2 s. c om DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (Exception e) { log.error("error: ", e); throw new IOException("Exception occured during creation of error message: " + e); } DOMImplementation di = db.getDOMImplementation(); // <!DOCTYPE ServiceExceptionReport SYSTEM "http://schemas.opengeospatial.net/wms/1.1.1/exception_1_1_1.dtd" // <!-- end of DOCTYPE declaration --> DocumentType dt = di.createDocumentType("ServiceExceptionReport", null, CallWMSServlet.EXCEPTION_DTD); Document dom = di.createDocument(null, "ServiceExceptionReport", dt); Element rootElement = dom.getDocumentElement(); rootElement.setAttribute("version", "1.1.1"); Element serviceExceptionElement = dom.createElement("ServiceException"); String exceptionName = ex.getClass().getName(); String message = ex.getMessage(); Throwable cause = ex.getCause(); serviceExceptionElement.setAttribute("code", exceptionName); CDATASection cdata = null; if (cause != null) { cdata = dom.createCDATASection(message + " - " + cause); } else { cdata = dom.createCDATASection(message); } serviceExceptionElement.appendChild(cdata); rootElement.appendChild(serviceExceptionElement); OutputFormat format = new OutputFormat(dom); format.setIndenting(true); output = new ByteArrayOutputStream(); XMLSerializer serializer = new XMLSerializer(output, format); serializer.serialize(dom); DOMValidator dv = new DOMValidator(); try { dv.parseAndValidate(new ByteArrayInputStream(output.toString().getBytes(KBConfiguration.CHARSET))); } catch (Exception e) { log.error("error: ", e); throw new IOException("Exception occured during validation of error message: " + e); } data.setHeader("Content-Disposition", "inline; filename=\"ServiceException.xml\";"); data.write(output); }
From source file:nl.b3p.kaartenbalie.service.servlet.GeneralServlet.java
/** * * @param request/*www . j ava 2 s . com*/ * @return * @throws java.io.UnsupportedEncodingException * @throws javax.xml.parsers.ParserConfigurationException * @throws org.xml.sax.SAXException * @throws java.io.IOException * @throws ValidationException * @throws java.lang.Exception */ protected OGCRequest calcOGCRequest(HttpServletRequest request) throws UnsupportedEncodingException, ParserConfigurationException, SAXException, IOException, ValidationException, Exception { OGCRequest ogcrequest; StringBuffer baseUrl = createBaseUrl(request); String iUrl = completeUrl(baseUrl, request).toString(); if (request.getMethod().equalsIgnoreCase("GET")) { ogcrequest = new OGCRequest(iUrl); log.debug("Incoming Get URL: " + iUrl); } else if (request.getMethod().equalsIgnoreCase("POST") && request.getParameter(OGCConstants.SERVICE) != null && request.getParameter(OGCConstants.SERVICE).equalsIgnoreCase(OGCConstants.WMS_SERVICE_WMS)) { ogcrequest = new OGCRequest(iUrl); Enumeration params = request.getParameterNames(); while (params.hasMoreElements()) { String paramName = (String) params.nextElement(); String paramValue = request.getParameter(paramName); //Parameters zijn niet UTF8. if (paramName.equalsIgnoreCase("onload") || paramName.equalsIgnoreCase("ondata") || paramName.equalsIgnoreCase("loadmovie") || paramName.equalsIgnoreCase("oldloadmovie")) { //do nothing } else { ogcrequest.addOrReplaceParameter(paramName, paramValue); } } log.debug("Incoming POST converted to GET URL: " + ogcrequest.getUrlWithNonOGCparams()); } else { log.debug("Incoming POST URL (content follows): " + iUrl); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(request.getInputStream()); ogcrequest = new OGCRequest(doc.getDocumentElement(), baseUrl.toString()); log.debug("Incoming POST content: \n" + OgcWfsClient.elementToString(doc.getDocumentElement())); } ogcrequest.setHttpMethod(request.getMethod()); return ogcrequest; }
From source file:nl.imvertor.common.file.XmlFile.java
/** * Build a DOM Document representation of some external XML file. * /*from w w w. j a v a 2 s. com*/ * @return * @throws Exception */ private Document buildDom(File file) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); InputSource in = new InputSource(file.getAbsolutePath()); docFactory.setValidating(validate); docFactory.setXIncludeAware(xinclude); docFactory.setFeature(VALIDATION_FEATURE_ID, validate); docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace); docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema); docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck); docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external); docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external); DocumentBuilder db = docFactory.newDocumentBuilder(); return db.parse(in); }
From source file:nl.imvertor.common.file.XmlFile.java
public boolean isWellFormed() { messages.removeAllElements();//from www . jav a 2 s. c o m try { wfcode = WFCODE_OKAY; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); factory.setXIncludeAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(this); builder.parse(new InputSource(this.getCanonicalPath())); } catch (Exception e) { wfcode = WFCODE_FATAL; } return wfcode < WFCODE_ERROR; }