List of usage examples for javax.xml.parsers DocumentBuilder getDOMImplementation
public abstract DOMImplementation getDOMImplementation();
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
private void saveWatchlists() { try {//from www. ja v a2 s . c o m DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); root.setAttribute("nextId", String.valueOf(watchlistsNextId)); //$NON-NLS-1$ for (Iterator iter = watchlistsMap.values().iterator(); iter.hasNext();) { Watchlist watchlist = (Watchlist) iter.next(); Element element = document.createElement("watchlist"); //$NON-NLS-1$ element.setAttribute("id", String.valueOf(watchlist.getId())); //$NON-NLS-1$ root.appendChild(element); Element node = document.createElement("title"); //$NON-NLS-1$ node.appendChild(document.createTextNode(watchlist.getDescription())); element.appendChild(node); node = document.createElement("style"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(watchlist.getStyle()))); element.appendChild(node); if (watchlist.getCurrency() != null) { node = document.createElement("currency"); //$NON-NLS-1$ node.appendChild(document.createTextNode(watchlist.getCurrency().getCurrencyCode())); element.appendChild(node); } if (watchlist.getDefaultFeed() != null) { node = document.createElement("feed"); //$NON-NLS-1$ node.appendChild(document.createTextNode(watchlist.getDefaultFeed())); element.appendChild(node); } Element columnsNode = document.createElement("columns"); //$NON-NLS-1$ element.appendChild(columnsNode); for (Iterator iter2 = watchlist.getColumns().iterator(); iter2.hasNext();) { WatchlistColumn column = (WatchlistColumn) iter2.next(); Element columnNode = document.createElement("column"); //$NON-NLS-1$ columnNode.setAttribute("id", column.getId()); //$NON-NLS-1$ columnsNode.appendChild(columnNode); } Element itemsNode = document.createElement("items"); //$NON-NLS-1$ element.appendChild(itemsNode); int itemIndex = 1; for (Iterator itemIter = watchlist.getItems().iterator(); itemIter.hasNext();) { WatchlistItem item = (WatchlistItem) itemIter.next(); item.setId(new Integer(itemIndex++)); item.setParent(watchlist); item.setRepository(this); Element itemNode = document.createElement("security"); //$NON-NLS-1$ itemNode.setAttribute("id", String.valueOf(item.getSecurity().getId())); //$NON-NLS-1$ itemsNode.appendChild(itemNode); if (item.getPosition() != null && item.getPosition().intValue() != 0) { node = document.createElement("position"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(item.getPosition()))); itemNode.appendChild(node); } if (item.getPaidPrice() != null && item.getPaidPrice().doubleValue() != 0) { node = document.createElement("paid"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(item.getPaidPrice()))); itemNode.appendChild(node); } int alertIndex = 1; for (Iterator alertIter = item.getAlerts().iterator(); alertIter.hasNext();) { Alert alert = (Alert) alertIter.next(); alert.setId(new Integer(alertIndex++)); Element alertNode = document.createElement("alert"); //$NON-NLS-1$ alertNode.setAttribute("pluginId", alert.getPluginId()); //$NON-NLS-1$ if (alert.getLastSeen() != null) alertNode.setAttribute("lastSeen", dateTimeFormat.format(alert.getLastSeen())); //$NON-NLS-1$ alertNode.setAttribute("popup", String.valueOf(alert.isPopup())); //$NON-NLS-1$ alertNode.setAttribute("hilight", String.valueOf(alert.isHilight())); //$NON-NLS-1$ itemNode.appendChild(alertNode); for (Iterator paramIter = alert.getParameters().keySet().iterator(); paramIter.hasNext();) { String key = (String) paramIter.next(); node = document.createElement("param"); //$NON-NLS-1$ node.setAttribute("key", key); //$NON-NLS-1$ node.appendChild(document.createTextNode((String) alert.getParameters().get(key))); alertNode.appendChild(node); } } } } saveDocument(document, "", "watchlists.xml"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { log.error(e.toString(), e); } }
From source file:com.amalto.workbench.utils.Util.java
/** * Returns a namespaced root element of a document Useful to create a namespace holder element * /*w w w. ja v a2 s. c o m*/ * @param namespace * @return the root Element */ public static Element getRootElement(String elementName, String namespace, String prefix) throws Exception { Element rootNS = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Document namespaceHolder = impl.createDocument(namespace, (prefix == null ? "" : prefix + ":") + elementName, null);//$NON-NLS-1$//$NON-NLS-2$ rootNS = namespaceHolder.getDocumentElement(); rootNS.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace);//$NON-NLS-1$//$NON-NLS-2$ } catch (Exception e) { String err = Messages.Util_11 + e.getLocalizedMessage(); throw new Exception(err); } return rootNS; }
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/*from w w w . java 2 s. com*/ * @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);//www . j a v a2 s. c om dbf.setNamespaceAware(true); 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:org.asimba.idp.profile.catalog.saml2.SAML2Catalog.java
/** * Private helper to clone XMLObjects/*from w w w . j a v a 2 s . c o m*/ * @param oSource * @return * @throws OAException */ private <T extends XMLObject> T cloneXMLObject(XMLObject oSource) throws MarshallingException, UnmarshallingException { Marshaller oMarshaller = Configuration.getMarshallerFactory().getMarshaller(oSource); try { if (oMarshaller == null) { _oLogger.warn("Unknown element '" + oSource.getElementQName() + "'; no marshaller available"); return null; } // go through process of creating a new Document as intermediate: DocumentBuilderFactory oDBFactory = DocumentBuilderFactory.newInstance(); oDBFactory.setNamespaceAware(true); DocumentBuilder oDocBuilder = oDBFactory.newDocumentBuilder(); DOMImplementation oDOMImpl = oDocBuilder.getDOMImplementation(); Document oDocument = oDOMImpl.createDocument(null, null, null); Element elSource = oSource.getDOM(); // Element elSource = oMarshaller.marshall(oSource, oDocument); // is this right: .getDOM() ?? Element clonedElement = (Element) elSource.cloneNode(true); // deep clone Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(clonedElement); T clonedXMLObject = (T) unmarshaller.unmarshall(clonedElement); return clonedXMLObject; // } catch (MarshallingException e) { // _oLogger.warn("Could not marshall element '"+oSource.getElementQName()+"'"); // return null; } catch (UnmarshallingException e) { _oLogger.warn("Could not unmarshall element '" + oSource.getElementQName() + "'"); return null; } catch (ParserConfigurationException e) { _oLogger.warn("Exception when creating intermedia document for cloning: " + e.getMessage()); return null; } }
From source file:org.htmlcleaner.XWikiDOMSerializer.java
/** * @param documentDocumentBuilder the {@link DocumentBuilder} instance to use, DocumentBuilder is not garantied to * be thread safe so at most the safe instance should be used only in the same thread * @param rootNode the HTML Cleaner root node to serialize * @return the W3C Document object/*from ww w . j av a 2s . co m*/ * @throws ParserConfigurationException if there's an error during serialization */ public Document createDOM(DocumentBuilder documentDocumentBuilder, TagNode rootNode) throws ParserConfigurationException { DOMImplementation impl = documentDocumentBuilder.getDOMImplementation(); // Copied from the source code of HTML Cleaner. Document document; // // Where a DOCTYPE is supplied in the input, ensure that this is in the output DOM. See issue #27 // // Note that we may want to fix incorrect DOCTYPEs in future; there are some fairly // common patterns for errors with the older HTML4 doctypes. // if (rootNode.getDocType() != null) { String qualifiedName = rootNode.getDocType().getPart1(); String publicId = rootNode.getDocType().getPublicId(); String systemId = rootNode.getDocType().getSystemId(); // // If there is no qualified name, set it to html. See bug #153. // if (qualifiedName == null) { qualifiedName = HTML_TAG_NAME; } DocumentType documentType = impl.createDocumentType(qualifiedName, publicId, systemId); // // While the qualified name is "HTML" for some DocTypes, we want the actual document root name to be "html". // See bug #116 // if (qualifiedName.equals("HTML")) { qualifiedName = HTML_TAG_NAME; } document = impl.createDocument(rootNode.getNamespaceURIOnPath(""), qualifiedName, documentType); } else { document = documentDocumentBuilder.newDocument(); Element rootElement = document.createElement(rootNode.getName()); document.appendChild(rootElement); } // // Copy across root node attributes - see issue 127. Thanks to rasifiel for the patch // Map<String, String> attributes = rootNode.getAttributes(); Iterator<Map.Entry<String, String>> entryIterator = attributes.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, String> entry = entryIterator.next(); String attrName = entry.getKey(); String attrValue = entry.getValue(); if (escapeXml) { attrValue = Utils.escapeXml(attrValue, props, true); } document.getDocumentElement().setAttribute(attrName, attrValue); // // Flag the attribute as an ID attribute if appropriate. Thanks to Chris173 // if (attrName.equalsIgnoreCase("id")) { document.getDocumentElement().setIdAttribute(attrName, true); } } createSubnodes(document, document.getDocumentElement(), rootNode.getAllChildren()); return document; }
From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java
private String getEvaluationResult(String response) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false);/*from w w w.j av a 2s. co m*/ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(response))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/result/value/text()"); String textValue = expr.evaluate(doc); if (!"".equals(textValue)) return textValue; expr = xpath.compile("/result/text()"); String resultingXmlAsText = expr.evaluate(doc); if (!"".equals(resultingXmlAsText.trim())) return resultingXmlAsText; expr = xpath.compile("/result/child::*"); Element node = (Element) expr.evaluate(doc, NODE); if (node != null) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String nodeName = attribute.getNodeName(); String nodeValue = attribute.getNodeValue(); if (XMLNS.equals(nodeName) && SERIALIZED_NAMESPACE.equals(nodeValue)) { node.removeAttribute(XMLNS); } } return prettyPrint(node, builder.getDOMImplementation()); } else { return response; } }
From source file:org.jboss.loom.utils.as7.AS7ModuleUtils.java
private static Document createDoc(String namespace, String rootElmName) throws ParserConfigurationException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); // Need specifically Xerces as it treats namespaces better way. /*DocumentBuilderFactory domFactory; try {/*from w w w . j a va 2 s . c o m*/ domFactory = (DocumentBuilderFactory) Class.forName("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl").newInstance(); } catch( ClassNotFoundException | InstantiationException | IllegalAccessException ex ) { throw new IllegalStateException("JDK's DocumentBuilderFactoryImpl not found:\n " + ex.getMessage(), ex ); }*/ //DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", ClassLoader.getSystemClassLoader()); domFactory.setIgnoringComments(true); domFactory.setNamespaceAware(false); domFactory.setValidating(false); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.getDOMImplementation().createDocument(namespace, rootElmName, null);// rootElmName return doc; }
From source file:org.oclc.oai.harvester.verb.HarvesterVerb.java
/** * Mock object creator (for unit testing purposes) *//*from w w w . j av a2 s . c o m*/ public HarvesterVerb() { try { /* Load DOM Document */ factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Thread t = Thread.currentThread(); DocumentBuilder builder = factory.newDocumentBuilder(); builderMap.put(t, builder); DOMImplementation impl = builder.getDOMImplementation(); Document namespaceHolder = impl.createDocument("http://www.oclc.org/research/software/oai/harvester", "harvester:namespaceHolder", null); namespaceElement = namespaceHolder.getDocumentElement(); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:harvester", "http://www.oclc.org/research/software/oai/harvester"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai20", "http://www.openarchives.org/OAI/2.0/"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_GetRecord", "http://www.openarchives.org/OAI/1.1/OAI_GetRecord"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_Identify", "http://www.openarchives.org/OAI/1.1/OAI_Identify"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_ListIdentifiers", "http://www.openarchives.org/OAI/1.1/OAI_ListIdentifiers"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_ListMetadataFormats", "http://www.openarchives.org/OAI/1.1/OAI_ListMetadataFormats"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_ListRecords", "http://www.openarchives.org/OAI/1.1/OAI_ListRecords"); namespaceElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:oai11_ListSets", "http://www.openarchives.org/OAI/1.1/OAI_ListSets"); } catch (Exception e) { e.printStackTrace(); } }
From source file:ORG.oclc.os.SRW.SRUServerTester.java
public SRUServerTester(String baseURL) { if (baseURL.endsWith("?")) baseURL = baseURL.substring(0, baseURL.length() - 1); this.baseURL = baseURL; // set up a document purely to hold the namespace mappings try {/* w w w .ja v a2 s . c om*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Document namespaceHolder = impl.createDocument("http://namespaces.cafeconleche.org/xmljava/ch3/", "f:namespaceMapping", null); ns = namespaceHolder.getDocumentElement(); ns.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:srw", "http://www.loc.gov/zing/srw/"); ns.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:exp", "http://explain.z3950.org/dtd/2.0/"); ns.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:diag", "http://www.loc.gov/zing/srw/diagnostic/"); } catch (ParserConfigurationException e) { log.error("unable to build namespace record)", e); } catch (DOMException e) { log.error("unable to build namespace record)", e); } }