List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.weaforce.system.component.fckeditor.response.XmlResponse.java
/** * Use this contructor if want to respond a positive message. * /*from w w w. j a v a2 s . c o m*/ * @param command * @param resourceType * @param currentFolder * @param constructedUrl */ public XmlResponse(CommandHandler command, ResourceTypeHandler resourceType, String currentFolder, String constructedUrl) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } Element root = document.createElement("Connector"); document.appendChild(root); root.setAttribute("command", command.toString()); root.setAttribute("resourceType", resourceType.toString()); Element currentFolderElement = document.createElement("CurrentFolder"); currentFolderElement.setAttribute("path", currentFolder); currentFolderElement.setAttribute("url", constructedUrl); root.appendChild(currentFolderElement); }
From source file:hoot.services.controllers.osm.MapResource.java
private static Document generateExtentOSM(String maxlon, String maxlat, String minlon, String minlat) { SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date now = new Date(); String strDate = sdfDate.format(now); try {/*w w w.j av a 2 s.c o m*/ DocumentBuilderFactory dbf = XmlDocumentBuilder.getSecureDocBuilderFactory(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element osmElem = doc.createElement("osm"); osmElem.setAttribute("version", "0.6"); osmElem.setAttribute("generator", "hootenanny"); doc.appendChild(osmElem); Element boundsElem = doc.createElement("bounds"); boundsElem.setAttribute("minlat", minlat); boundsElem.setAttribute("minlon", minlon); boundsElem.setAttribute("maxlat", maxlat); boundsElem.setAttribute("maxlon", maxlon); osmElem.appendChild(boundsElem); // The ID's for these fabricated nodes were stepping on the ID's of actual nodes, so their ID's need to be // made negative and large, so they have no chance of stepping on anything. long node1Id = Long.MIN_VALUE + 3; long node2Id = Long.MIN_VALUE + 2; long node3Id = Long.MIN_VALUE + 1; long node4Id = Long.MIN_VALUE; Element nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node1Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", maxlat); nodeElem.setAttribute("lon", minlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node2Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", maxlat); nodeElem.setAttribute("lon", maxlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node3Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", minlat); nodeElem.setAttribute("lon", maxlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node4Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", minlat); nodeElem.setAttribute("lon", minlon); osmElem.appendChild(nodeElem); Element wayElem = doc.createElement("way"); wayElem.setAttribute("id", String.valueOf(Long.MIN_VALUE)); wayElem.setAttribute("timestamp", strDate); wayElem.setAttribute("user", "hootenannyuser"); wayElem.setAttribute("visible", "true"); wayElem.setAttribute("version", "1"); Element ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node1Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node2Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node3Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node4Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node1Id)); wayElem.appendChild(ndElem); /* * ndElem = doc.createElement("tag"); ndElem.setAttribute("k", "area"); * ndElem.setAttribute("v", "yes"); wayElem.appendChild(ndElem); */ osmElem.appendChild(wayElem); Transformer tf = TransformerFactory.newInstance().newTransformer(); // Fortify may require this, but it doesn't work. // TransformerFactory transformerFactory = // XmlDocumentBuilder.getSecureTransformerFactory(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); try (Writer out = new StringWriter()) { tf.transform(new DOMSource(doc), new StreamResult(out)); logger.debug("Layer Extent OSM: {}", out); } return doc; } catch (Exception e) { throw new RuntimeException("Error generating OSM extent", e); } }
From source file:erwins.util.repack.xml.XMLBuilder.java
/** * Construct a builder for new XML document with a default namespace. * The document will be created with the given root element, and the builder * returned by this method will serve as the starting-point for any further * document additions.//from www .j a v a2s .c o m * * @param name * the name of the document's root element. * @param namespaceURI * default namespace URI for document, ignored if null or empty. * @return * a builder node that can be used to add more nodes to the XML document. * * @throws FactoryConfigurationError * @throws ParserConfigurationException */ public static XMLBuilder create(String name, String namespaceURI) throws ParserConfigurationException, FactoryConfigurationError { // Init DOM builder and Document. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(isNamespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = null; if (namespaceURI != null && namespaceURI.length() > 0) { rootElement = document.createElementNS(namespaceURI, name); } else { rootElement = document.createElement(name); } document.appendChild(rootElement); return new XMLBuilder(document); }
From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java
private Element entry(final AtomEntry entry) throws ParserConfigurationException { final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element entryElem = doc.createElement(ODataConstants.ATOM_ELEM_ENTRY); entryElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM); entryElem.setAttribute(ODataConstants.XMLNS_METADATA, client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA)); entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES)); entryElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML); entryElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS); if (entry.getBaseURI() != null) { entryElem.setAttribute(ODataConstants.ATTR_XMLBASE, entry.getBaseURI().toASCIIString()); }// w ww . jav a2 s. com doc.appendChild(entryElem); final Element category = doc.createElement(ODataConstants.ATOM_ELEM_CATEGORY); category.setAttribute(ODataConstants.ATOM_ATTR_TERM, entry.getType()); category.setAttribute(ODataConstants.ATOM_ATTR_SCHEME, client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_SCHEME)); entryElem.appendChild(category); if (StringUtils.isNotBlank(entry.getTitle())) { final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE); title.appendChild(doc.createTextNode(entry.getTitle())); entryElem.appendChild(title); } if (StringUtils.isNotBlank(entry.getSummary())) { final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY); summary.appendChild(doc.createTextNode(entry.getSummary())); entryElem.appendChild(summary); } setLinks(entryElem, entry.getAssociationLinks()); setLinks(entryElem, entry.getNavigationLinks()); setLinks(entryElem, entry.getMediaEditLinks()); final Element content = doc.createElement(ODataConstants.ATOM_ELEM_CONTENT); if (entry.isMediaEntry()) { if (StringUtils.isNotBlank(entry.getMediaContentType())) { content.setAttribute(ODataConstants.ATTR_TYPE, entry.getMediaContentType()); } if (StringUtils.isNotBlank(entry.getMediaContentSource())) { content.setAttribute(ODataConstants.ATOM_ATTR_SRC, entry.getMediaContentSource()); } if (content.getAttributes().getLength() > 0) { entryElem.appendChild(content); } if (entry.getMediaEntryProperties() != null) { entryElem.appendChild(doc.importNode(entry.getMediaEntryProperties(), true)); } } else { content.setAttribute(ODataConstants.ATTR_TYPE, ContentType.APPLICATION_XML.getMimeType()); if (entry.getContent() != null) { content.appendChild(doc.importNode(entry.getContent(), true)); } entryElem.appendChild(content); } return entryElem; }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * //from ww w . j ava 2s . c o m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExact(String model, String name, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExact: " + model + " name: " + name + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dc:title", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); } if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dcterms:alternative", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); client = new HttpClient(); method = new GetMethod(queryUrl); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); } if (method.getStatusCode() == 200) { results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); } if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder .parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; //throw new RuntimeException(e); } }
From source file:net.sf.joost.emitter.DOMEmitter.java
/** * DefaultConstructor//from w w w. ja va 2 s . c o m * * @throws ParserConfigurationException * if an error occurs while creating * {@link javax.xml.parsers.DocumentBuilder} * DOM-DocumentBuilder */ public DOMEmitter(DOMResult result) throws ParserConfigurationException { if (DEBUG) log.debug("init DOMEmitter"); Node rootNode = result.getNode(); nextSiblingOfRootNodes = result.getNextSibling(); if (rootNode != null) { // use the document of the provided node if (rootNode instanceof Document) document = (Document) rootNode; else document = rootNode.getOwnerDocument(); stack.push(rootNode); } else { // create a new document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); document = docBuilder.newDocument(); stack.push(document); } }
From source file:ca.mcgill.music.ddmal.mei.MeiXmlWriter.java
/** * Create a writer for the specified document. * @param doc/*from ww w . j a v a 2 s. co m*/ * the document to write. */ private MeiXmlWriter(MeiDocument doc) { this.meiDocument = doc; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } document = builder.newDocument(); }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * //from ww w . ja v a 2 s .c o m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "=" + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); } if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); } if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; //throw new RuntimeException(e); } }
From source file:de.mpg.escidoc.services.common.util.Util.java
/** * Queries CoNE service and returns the result as DOM node. * The returned XML has the following structure: * <cone>/*from w w w . j a v a 2 s . c o m*/ * <author> * <familyname>Buxtehude-Mlln</familyname> * <givenname>Heribert</givenname> * <prefix>von und zu</prefix> * <title>Knig</title> * </author> * <author> * <familyname>Mller</familyname> * <givenname>Peter</givenname> * </author> * </authors> * * @param Single instituteId for an institute without departments or list of Ids. Every department has his own Id. * @return */ public static Node queryReportPersonCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl; List<String> childIds = new ArrayList<String>(); // get the childOUs if any in the query if (query.contains(" ")) { String[] result = query.split("\\s+"); for (String s : result) { childIds.add(s); } } try { documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&escidoc:position/dc:identifier=\"" + query + "\"&n=0"; HttpClient client = new HttpClient(); if (childIds.size() > 0) { // execute a method for every child ou for (String childId : childIds) { queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&escidoc:position/dc:identifier=\"" + childId + "\"&n=0"; executeGetMethod(client, queryUrl, documentBuilder, document, element); } } else { // there are no child ous, methid is called once executeGetMethod(client, queryUrl, documentBuilder, document, element); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken."); return null; } }
From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java
@Override protected JSONProperty doDeserializeV4(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser); final JSONProperty property = new JSONProperty(); try {//w w w.jav a2 s .co m final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); Element content = document.createElement(ODataConstants.ELEM_PROPERTY); JsonNode subtree = null; if (tree.has(ODataConstants.JSON_VALUE)) { if (tree.has(v4AnnotationPrefix + ODataConstants.JSON_TYPE) && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(v4AnnotationPrefix + ODataConstants.JSON_TYPE).asText()); } final JsonNode value = tree.get(ODataConstants.JSON_VALUE); if (value.isValueNode()) { content.appendChild(document.createTextNode(value.asText())); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { subtree = tree.objectNode(); ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE)); if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { subtree = tree.get(ODataConstants.JSON_VALUE); } } else { subtree = tree; } if (subtree != null) { DOMTreeUtilsV4.buildSubtree(content, subtree); } final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE); if (children.size() == 1) { final Element value = (Element) children.iterator().next(); if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) { if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { value.setAttribute(ODataConstants.ATTR_M_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } content = value; } } property.setContent(content); } catch (ParserConfigurationException e) { throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e); } return property; }