List of usage examples for org.w3c.dom Document createElement
public Element createElement(String tagName) throws DOMException;
From source file:com.connexta.arbitro.utils.PolicyUtils.java
/** * This method creates a policy set element of the XACML policy * @param policyElementDTO policy element data object * @param doc XML document/*from w ww . j a v a 2 s. c o m*/ * @return policyElement * @throws PolicyBuilderException if */ public static Element createPolicySetElement(PolicySetElementDTO policyElementDTO, Document doc) throws PolicyBuilderException { Element policyElement = doc.createElement(PolicyConstants.POLICY_SET_ELEMENT); policyElement.setAttribute("xmlns", PolicyConstants.XACMLData.XACML3_POLICY_NAMESPACE); if (policyElementDTO.getPolicySetId() != null && policyElementDTO.getPolicySetId().trim().length() > 0) { policyElement.setAttribute(PolicyConstants.POLICY_SET_ID, policyElementDTO.getPolicySetId()); } else { throw new PolicyBuilderException("Policy name can not be null"); } if (policyElementDTO.getPolicyCombiningAlgId() != null && policyElementDTO.getPolicyCombiningAlgId().trim().length() > 0) { policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM, policyElementDTO.getPolicyCombiningAlgId()); } else { policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM, PolicyConstants.PolicyCombiningAlog.DENY_OVERRIDE_ID); // TODO log.warn("Rule combining algorithm is not defined. Use default algorithm; Deny Override"); } if (policyElementDTO.getVersion() != null && policyElementDTO.getVersion().trim().length() > 0) { policyElement.setAttribute(PolicyConstants.POLICY_VERSION, policyElementDTO.getVersion()); } else { // policy version is can be handled by policy registry. therefore we can ignore it, although it // is a required attribute policyElement.setAttribute(PolicyConstants.POLICY_VERSION, "1.0"); } if (policyElementDTO.getDescription() != null && policyElementDTO.getDescription().trim().length() > 0) { Element descriptionElement = doc.createElement(PolicyConstants.DESCRIPTION_ELEMENT); descriptionElement.setTextContent(policyElementDTO.getDescription()); policyElement.appendChild(descriptionElement); } TargetElementDTO targetElementDTO = policyElementDTO.getTargetElementDTO(); List<ObligationElementDTO> obligationElementDTOs = policyElementDTO.getObligationElementDTOs(); if (targetElementDTO != null) { policyElement.appendChild(createTargetElement(targetElementDTO, doc)); } else { policyElement.appendChild(doc.createElement(PolicyConstants.TARGET_ELEMENT)); } List<String> policySets = policyElementDTO.getPolicySets(); if (policySets != null && policySets.size() > 0) { // TODO } List<String> policies = policyElementDTO.getPolicies(); if (policies != null && policies.size() > 0) { // TODO } List<String> policySetIds = policyElementDTO.getPolicySetIdReferences(); if (policySetIds != null && policySetIds.size() > 0) { for (String policySetId : policySetIds) { Element element = doc.createElement(PolicyConstants.POLICY_SET_ID_REFERENCE_ELEMENT); element.setTextContent(policySetId); policyElement.appendChild(element); } } List<String> policyIds = policyElementDTO.getPolicyIdReferences(); if (policyIds != null && policyIds.size() > 0) { for (String policyId : policyIds) { Element element = doc.createElement(PolicyConstants.POLICY_ID_REFERENCE_ELEMENT); element.setTextContent(policyId); policyElement.appendChild(element); } } if (obligationElementDTOs != null && obligationElementDTOs.size() > 0) { List<ObligationElementDTO> obligations = new ArrayList<ObligationElementDTO>(); List<ObligationElementDTO> advices = new ArrayList<ObligationElementDTO>(); for (ObligationElementDTO obligationElementDTO : obligationElementDTOs) { if (obligationElementDTO.getType() == ObligationElementDTO.ADVICE) { advices.add(obligationElementDTO); } else { obligations.add(obligationElementDTO); } } Element obligation = createObligationsElement(obligations, doc); Element advice = createAdvicesElement(advices, doc); if (obligation != null) { policyElement.appendChild(obligation); } if (advice != null) { policyElement.appendChild(advice); } } return policyElement; }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Updates content of atom feed header file by re-creating new xml header block and writing it * into given file. Actually, if given atom feed header file does not exists, it creates it. * Otherwise, it changes values of "updated", "versionId" and "entriesSize" elements within * header xml tree./*from www . j av a 2 s. c o m*/ * * @param atomfeedheader the file target to be updated * @param entriesSize the size in bytes of entries payload, which is related to given feed * header */ private static void updateFeedFileHeader(File atomfeedheader, long entriesSize) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("feed"); root.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(root); // create title element, add its text, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_TITLE); title.appendChild(titleText); root.appendChild(title); // create title element, add its attrs, and add to root Element selflink = doc.createElement("link"); selflink.setAttribute("href", AtomFeedUtil.getFeedUrl()); selflink.setAttribute("rel", "self"); root.appendChild(selflink); Element serverlink = doc.createElement("link"); serverlink.setAttribute("href", getWebServiceUrl()); root.appendChild(serverlink); // create title element, add its text, and add to root Element id = doc.createElement("id"); Text idText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_ID); id.appendChild(idText); root.appendChild(id); // create updated element, add its text, and add to root Element updated = doc.createElement("updated"); Date lastModified = new Date(); Text updatedText = doc.createTextNode(dateToRFC3339(lastModified)); updated.appendChild(updatedText); root.appendChild(updated); // create versionId element, add its text, and add to root Element versionId = doc.createElement("versionId"); Text versionIdText = doc.createTextNode(String.valueOf(lastModified.getTime())); versionId.appendChild(versionIdText); root.appendChild(versionId); // create versionId element, add its text, and add to root Element entriesSizeElement = doc.createElement("entriesSize"); Text entriesSizeText = doc.createTextNode(String.valueOf(entriesSize)); entriesSizeElement.appendChild(entriesSizeText); root.appendChild(entriesSizeElement); /* * Print the xml to the file */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "no"); // create string from xml tree FileWriter fw = new FileWriter(atomfeedheader); StreamResult result = new StreamResult(fw); DOMSource source = new DOMSource(doc); trans.transform(source, result); // print xml for debugging purposes if (log.isTraceEnabled()) { StringWriter sw = new StringWriter(); result = new StreamResult(sw); trans.transform(source, result); log.trace("Here's the initial xml:\n\n" + sw.toString()); } } catch (Exception e) { log.error("unable to initialize feed at: " + atomfeedheader.getAbsolutePath(), e); } }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Converts the given object to an xml entry * //from w w w. j a v a2s . c o m * @param action what is happenening * @param object the object being changed * @return atom feed xml entry string * @should return valid entry xml data */ protected static String getEntry(String action, OpenmrsObject object) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("entry"); doc.appendChild(root); // the title element is REQUIRED // create title element, add object class, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(action + ":" + object.getClass().getName()); title.appendChild(titleText); root.appendChild(title); // create link to view object details Element link = doc.createElement("link"); link.setAttribute("href", AtomFeedUtil.getViewUrl(object)); root.appendChild(link); // the id element is REQUIRED // create id element Element id = doc.createElement("id"); Text idText = doc.createTextNode("urn:uuid:" + object.getUuid()); id.appendChild(idText); root.appendChild(id); // the updated element is REQUIRED // create updated element, set current date Element updated = doc.createElement("updated"); // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2 // instead? Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object))); updated.appendChild(updatedText); root.appendChild(updated); // the author element is REQUIRED // add author element, find creator Element author = doc.createElement("author"); Element name = doc.createElement("name"); Text nameText = doc.createTextNode(getAuthor(object)); name.appendChild(nameText); author.appendChild(name); root.appendChild(author); // the summary element is REQUIRED // add a summary Element summary = doc.createElement("summary"); Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action); summary.appendChild(summaryText); root.appendChild(summary); Element classname = doc.createElement("classname"); Text classnameText = doc.createTextNode(object.getClass().getName()); classname.appendChild(classnameText); root.appendChild(classname); Element actionElement = doc.createElement("action"); Text actionText = doc.createTextNode(action); actionElement.appendChild(actionText); root.appendChild(actionElement); /* * Print the xml to the string */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); return sw.toString(); } catch (Exception e) { log.error("unable to create entry string for: " + object); return ""; } }
From source file:com.connexta.arbitro.utils.PolicyUtils.java
/** * This creates XML representation of attribute designator Element using AttributeDesignatorDTO object * * @param attributeDesignatorDTO AttributeDesignatorDTO * @param doc Document/*from www . j av a 2 s . co m*/ * @return DOM element * @throws PolicyBuilderException throws */ public static Element createAttributeDesignatorElement(AttributeDesignatorDTO attributeDesignatorDTO, Document doc) throws PolicyBuilderException { String attributeDesignatorElementName = PolicyConstants.ATTRIBUTE_DESIGNATOR; Element attributeDesignatorElement = doc.createElement(attributeDesignatorElementName); String attributeId = attributeDesignatorDTO.getAttributeId(); String category = attributeDesignatorDTO.getCategory(); if (attributeId != null && attributeId.trim().length() > 0 && category != null && category.trim().length() > 0) { attributeDesignatorElement.setAttribute(PolicyConstants.ATTRIBUTE_ID, attributeDesignatorDTO.getAttributeId()); attributeDesignatorElement.setAttribute(PolicyConstants.CATEGORY, attributeDesignatorDTO.getCategory()); if (attributeDesignatorDTO.getDataType() != null && attributeDesignatorDTO.getDataType().trim().length() > 0) { attributeDesignatorElement.setAttribute(PolicyConstants.DATA_TYPE, attributeDesignatorDTO.getDataType()); } else { attributeDesignatorElement.setAttribute(PolicyConstants.DATA_TYPE, PolicyConstants.STRING_DATA_TYPE); } if (attributeDesignatorDTO.getIssuer() != null && attributeDesignatorDTO.getIssuer().trim().length() > 0) { attributeDesignatorElement.setAttribute(PolicyConstants.ISSUER, attributeDesignatorDTO.getIssuer()); } if (attributeDesignatorDTO.getMustBePresent() != null && attributeDesignatorDTO.getMustBePresent().trim().length() > 0) { attributeDesignatorElement.setAttribute(PolicyConstants.MUST_BE_PRESENT, attributeDesignatorDTO.getMustBePresent()); } else { attributeDesignatorElement.setAttribute(PolicyConstants.MUST_BE_PRESENT, "true"); } } else { throw new PolicyBuilderException("Category name can not be null"); // TODO } return attributeDesignatorElement; }
From source file:hoot.services.controllers.osm.ChangesetDbWriter.java
/** * Writes a changeset upload response to an XML document * * @param changesetId/*from w w w . j a va 2 s .co m*/ * ID of the uploaded changeset * @param changesetDiffElements * Elements that have been modified in the corresponding * changeset request * @return a changeset upload response XML document */ private static Document writeResponse(long changesetId, List<XmlSerializable> changesetDiffElements) { logger.debug("Building response..."); Document responseDoc = null; try { responseDoc = XmlDocumentBuilder.create(); } catch (ParserConfigurationException e) { throw new RuntimeException("Error creating XmlDocumentBuilder!", e); } org.w3c.dom.Element osmElement = OsmResponseHeaderGenerator.getOsmDataHeader(responseDoc); org.w3c.dom.Element diffResultXmlElement = responseDoc.createElement("diffResult"); diffResultXmlElement.setAttribute("generator", GENERATOR); diffResultXmlElement.setAttribute("version", OSM_VERSION); for (XmlSerializable element : changesetDiffElements) { diffResultXmlElement.appendChild(element.toChangesetResponseXml(diffResultXmlElement)); } osmElement.appendChild(diffResultXmlElement); responseDoc.appendChild(osmElement); return responseDoc; }
From source file:Main.java
/** * Clone given Node into target Document. If targe is null, same Document will be used. * If deep is specified, all children below will also be cloned. */// w w w . j av a 2 s . c o m public static Node cloneNode(Node node, Document target, boolean deep) throws DOMException { if (target == null || node.getOwnerDocument() == target) // same Document return node.cloneNode(deep); else { //DOM level 2 provides this in Document, so once xalan switches to that, //we can take out all the below and just call target.importNode(node, deep); //For now, we implement based on the javadocs for importNode Node newNode; int nodeType = node.getNodeType(); switch (nodeType) { case Node.ATTRIBUTE_NODE: newNode = target.createAttribute(node.getNodeName()); break; case Node.DOCUMENT_FRAGMENT_NODE: newNode = target.createDocumentFragment(); break; case Node.ELEMENT_NODE: Element newElement = target.createElement(node.getNodeName()); NamedNodeMap nodeAttr = node.getAttributes(); if (nodeAttr != null) for (int i = 0; i < nodeAttr.getLength(); i++) { Attr attr = (Attr) nodeAttr.item(i); if (attr.getSpecified()) { Attr newAttr = (Attr) cloneNode(attr, target, true); newElement.setAttributeNode(newAttr); } } newNode = newElement; break; case Node.ENTITY_REFERENCE_NODE: newNode = target.createEntityReference(node.getNodeName()); break; case Node.PROCESSING_INSTRUCTION_NODE: newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: newNode = target.createTextNode(node.getNodeValue()); break; case Node.CDATA_SECTION_NODE: newNode = target.createCDATASection(node.getNodeValue()); break; case Node.COMMENT_NODE: newNode = target.createComment(node.getNodeValue()); break; case Node.NOTATION_NODE: case Node.ENTITY_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.DOCUMENT_NODE: default: throw new IllegalArgumentException("Importing of " + node + " not supported yet"); } if (deep) for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) newNode.appendChild(cloneNode(child, target, true)); return newNode; } }
From source file:Main.java
/** * Clone given Node into target Document. If targe is null, same Document will be used. * If deep is specified, all children below will also be cloned. *///from ww w .j a v a 2 s. c o m public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException { if ((target == null) || (node.getOwnerDocument() == target)) { // same Document return node.cloneNode(deep); } else { //DOM level 2 provides this in Document, so once xalan switches to that, //we can take out all the below and just call target.importNode(node, deep); //For now, we implement based on the javadocs for importNode Node newNode; int nodeType = node.getNodeType(); switch (nodeType) { case Node.ATTRIBUTE_NODE: newNode = target.createAttribute(node.getNodeName()); break; case Node.DOCUMENT_FRAGMENT_NODE: newNode = target.createDocumentFragment(); break; case Node.ELEMENT_NODE: Element newElement = target.createElement(node.getNodeName()); NamedNodeMap nodeAttr = node.getAttributes(); if (nodeAttr != null) { for (int i = 0; i < nodeAttr.getLength(); i++) { Attr attr = (Attr) nodeAttr.item(i); if (attr.getSpecified()) { Attr newAttr = (Attr) cloneNode(attr, target, true); newElement.setAttributeNode(newAttr); } } } newNode = newElement; break; case Node.ENTITY_REFERENCE_NODE: newNode = target.createEntityReference(node.getNodeName()); break; case Node.PROCESSING_INSTRUCTION_NODE: newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: newNode = target.createTextNode(node.getNodeValue()); break; case Node.CDATA_SECTION_NODE: newNode = target.createCDATASection(node.getNodeValue()); break; case Node.COMMENT_NODE: newNode = target.createComment(node.getNodeValue()); break; case Node.NOTATION_NODE: case Node.ENTITY_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.DOCUMENT_NODE: default: throw new IllegalArgumentException("Importing of " + node + " not supported yet"); } if (deep) { for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { newNode.appendChild(cloneNode(child, target, true)); } } return newNode; } }
From source file:de.mpg.mpdl.inge.transformation.Util.java
public static Node getSize(String url) { DocumentBuilder documentBuilder; HttpClient httpClient = new HttpClient(); HeadMethod headMethod = new HeadMethod(url); try {/*from w w w .ja va 2 s.c o m*/ logger.info("Getting size of " + url); ProxyHelper.executeMethod(httpClient, headMethod); if (headMethod.getStatusCode() != 200) { logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url); } documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("size"); document.appendChild(element); Header header = headMethod.getResponseHeader("Content-Length"); logger.info("HEAD Request to " + url + " returned Content-Length: " + (header != null ? header.getValue() : null)); if (header != null) { element.setTextContent(header.getValue()); return document; } else { // did not get length via HEAD request, try to do a GET request // workaround for biomed central, where HEAD requests sometimes return Content-Length, // sometimes not logger.info("GET request to " + url + " did not return any Content-Length. Trying GET request."); httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); ProxyHelper.executeMethod(httpClient, getMethod); if (getMethod.getStatusCode() != 200) { logger.warn("Wrong status code " + getMethod.getStatusCode() + " at " + url); } InputStream is = getMethod.getResponseBodyAsStream(); long size = 0; while (is.read() != -1) { size++; } is.close(); logger.info("GET request to " + url + " returned a file with length: " + size); element.setTextContent(String.valueOf(size)); return document; } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.connexta.arbitro.utils.PolicyUtils.java
/** * This method creates a match elementof the XACML policy * @param matchElementDTO match element data object * @param doc XML document/* ww w . j a va 2 s. co m*/ * @return match Element * @throws PolicyBuilderException throws */ public static Element createMatchElement(MatchElementDTO matchElementDTO, Document doc) throws PolicyBuilderException { Element matchElement = null; if (matchElementDTO.getMatchId() != null && matchElementDTO.getMatchId().trim().length() > 0) { matchElement = doc.createElement(PolicyConstants.MATCH_ELEMENT); matchElement.setAttribute(PolicyConstants.MATCH_ID, matchElementDTO.getMatchId()); if (matchElementDTO.getAttributeValueElementDTO() != null) { Element attributeValueElement = createAttributeValueElement( matchElementDTO.getAttributeValueElementDTO(), doc); matchElement.appendChild(attributeValueElement); } if (matchElementDTO.getAttributeDesignatorDTO() != null) { Element attributeDesignatorElement = createAttributeDesignatorElement( matchElementDTO.getAttributeDesignatorDTO(), doc); matchElement.appendChild(attributeDesignatorElement); } if (matchElementDTO.getAttributeSelectorDTO() != null) { Element attributeSelectorElement = createAttributeSelectorElement( matchElementDTO.getAttributeSelectorDTO(), doc); matchElement.appendChild(attributeSelectorElement); } } return matchElement; }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries CoNE service and returns the result as DOM node. The returned XML has the following * structure: <cone> <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> * /*from w w w . j a v a2 s. c o m*/ * @param authors * @return */ public static Node queryCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl = null; try { logger.info("queryCone: " + model + " query: " + query); 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&q=" + URLEncoder.encode(query, "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 (method.getStatusCode() == 200) { String[] results = method.getResponseBodyAsString().split("\n"); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; // 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); if (coneSession != null) { detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, detailMethod); logger.info("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()); } } } } 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. (" + queryUrl + ") .Otherwise it should be clarified if any measures have to be taken.", e); logger.debug("Stacktrace", e); return null; // throw new RuntimeException(e); } }