List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:it.imtech.metadata.MetaUtility.java
private void addContributorToMetadata(String panelname) { try {/* ww w. j a v a 2 s . c om*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); //File backupmetadata = new File(Globals.SESSION_METADATA); doc = dBuilder.parse(backupmetadata); String expression = "//*[@ID='11']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); int maxseq = 0; int tmpseq = 0; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > maxseq) { maxseq = tmpseq; } } maxseq++; Node newNode = nodeList.item(0).cloneNode(true); Element nodetocopy = (Element) newNode; NamedNodeMap attr = nodeList.item(0).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); nodeAttr.setTextContent(Integer.toString(maxseq)); Node copyOfn = doc.importNode(nodetocopy, true); nodeList.item(0).getParentNode().appendChild(copyOfn); XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } }
From source file:it.imtech.metadata.MetaUtility.java
private void addClassificationToMetadata(String panelname) { try {/*from ww w.j a v a 2 s . c om*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); //File backupmetadata = new File(Globals.SESSION_METADATA); File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); doc = dBuilder.parse(backupmetadata); String expression = "//*[@ID='22']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); int maxseq = 0; int tmpseq; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > maxseq) { maxseq = tmpseq; } } maxseq++; Node newNode = nodeList.item(0).cloneNode(true); Element nodetocopy = (Element) newNode; NamedNodeMap attr = nodeList.item(0).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); nodeAttr.setTextContent(Integer.toString(maxseq)); Node copyOfn = doc.importNode(nodetocopy, true); nodeList.item(0).getParentNode().appendChild(copyOfn); Element root = doc.getDocumentElement(); NodeList firstlevelnodes = root.getChildNodes(); for (int i = 0; i < firstlevelnodes.getLength(); i++) { if (firstlevelnodes.item(i).getNodeType() == Node.ELEMENT_NODE) { Element node = (Element) firstlevelnodes.item(i); Integer sequence = Integer.parseInt(node.getAttribute("sequence")); if (!node.getAttribute("ID").equals("22") && sequence >= maxseq) { node.setAttribute("sequence", Integer.toString(sequence + 1)); } } } XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } }
From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java
private void appendContentSource(Document doc, ContentVersionEntity version) { ContentSourceXmlCreator contentSourceXmlCreator = new ContentSourceXmlCreator(contentIndexDao); XMLDocument sourceDocument = contentSourceXmlCreator.createSourceDocument(version); Element sourceEl = sourceDocument.getAsDOMDocument().getDocumentElement(); doc.getDocumentElement().appendChild(doc.importNode(sourceEl, true)); }
From source file:com.enonic.vertical.adminweb.AdminHandlerBaseServlet.java
protected Document applyChangesInAccessRights(Document docExistingAccessRights, Map<String, ExtendedMap> removedAccessRights, Map<String, ExtendedMap> modifiedAccessRights, Map<String, ExtendedMap> addedAccessRights) { // We have to make a clone of this hashtable, because we may have to remove some elements // and we don't want to affect this on the original hashtable. addedAccessRights = new HashMap<String, ExtendedMap>(addedAccessRights); //("removedAccessRights = " + removedAccessRights); //("modifiedAccessRights = " + modifiedAccessRights); //("addedAccessRights = " + addedAccessRights); Element elExistingAccessRights = docExistingAccessRights.getDocumentElement(); //("antall accessrights: " + elExistingAccessRights.getChildNodes().getLength()); // Loop thru existing accessrights and check if there is anyone to remove or modify Element curAccessRight = (Element) elExistingAccessRights.getFirstChild(); while (curAccessRight != null) { String groupKey = curAccessRight.getAttribute("groupkey"); //("checking accessright, groupkey = " + groupKey); boolean remove = removedAccessRights.containsKey(groupKey); boolean modify = modifiedAccessRights.containsKey(groupKey); boolean add = addedAccessRights.containsKey(groupKey); boolean overwrite = (modify || add); // Remove accessright if (remove) { //("removing accessright, groupkey = " + groupKey); curAccessRight = XMLTool.removeChildFromParent(elExistingAccessRights, curAccessRight); }/*from ww w .j ava2 s .c o m*/ // Overwrite accessright else if (overwrite) { ExtendedMap params; if (modify) { params = modifiedAccessRights.get(groupKey); //("modifying/overwriting accessright, groupkey = " + groupKey); } else // add == true: { params = addedAccessRights.get(groupKey); //("adding/overwriting accessright, groupkey = " + groupKey); } Document docNewAccessRight = XMLTool.createDocument("foo"); Element elNewAccessRight = buildAccessRightElement(docNewAccessRight, docNewAccessRight.getDocumentElement(), groupKey, params); Element imported = (Element) docExistingAccessRights.importNode(elNewAccessRight, true); elExistingAccessRights.replaceChild(imported, curAccessRight); curAccessRight = imported; // Hvis vi overskriver eksisterende rettighet i stedet for legge til, fordi den finnes fra fr // m vi fjerne rettigheten fra addedAccessRights, slik at vi ikke legger til den to ganger. if (add) { //("Found an accessright that we wanted to add, that existed - we overwrite it // inseated, and removes the groupkey ("+groupKey+")from the addAccessRights hashtable so that it // want be added later"); addedAccessRights.remove(groupKey); } // curAccessRight = (Element) curAccessRight.getNextSibling(); } else { curAccessRight = (Element) curAccessRight.getNextSibling(); } } // Add new accessrights for (Object addedAccessRightKey : addedAccessRights.keySet()) { String currentGroupKey = (String) addedAccessRightKey; //("adding new accessright, groupkey = " + currentGroupKey); ExtendedMap params = addedAccessRights.get(currentGroupKey); Document docNewAccessRight = XMLTool.createDocument("foo"); Element elNewAccessRight = buildAccessRightElement(docNewAccessRight, docNewAccessRight.getDocumentElement(), currentGroupKey, params); elExistingAccessRights.appendChild(docExistingAccessRights.importNode(elNewAccessRight, true)); } return docExistingAccessRights; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * If the xpath identifies multiple elements, it will only add to the first * element, if there is no such parent element, it will just add it... */// ww w . j av a 2 s.co m @Override public synchronized Map<String, Object> addSubElementToElementIdentifiedByXPath(final String parentElementXPath, final String originalXml, final String elementXml, boolean generateId) throws SAXException, IOException, XPathExpressionException { Assert.hasText(parentElementXPath); Assert.hasText(originalXml); Assert.hasText(elementXml); Document originalDom = parse(originalXml); Document finalDom = originalDom; Document elementDom = parse(elementXml); Element elementRoot = (Element) elementDom.getFirstChild(); XPath xPath = getXPathInstance(); // find all the nodes specified by xPathString in the finalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(parentElementXPath, finalDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); String id = ""; Element currentNode = finalDom.getDocumentElement(); if (el == 0) { // doesn't exist, create the parent... List<String> nodeList = getNodeList(parentElementXPath); // remove first one, should be protocol nodeList.remove(0); int c = 0; for (String n : nodeList) { NodeList cur = currentNode.getElementsByTagName(n); String curName = currentNode.getNodeName(); c = cur.getLength(); if (c > 1) { throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n); } if (c == 0) { logger.debug("empty node...; " + n + " doesn't exist under " + curName); Element newN = finalDom.createElement(n); currentNode.appendChild(newN); currentNode = newN; continue; } currentNode = (Element) cur.item(0); } } else if (el > 0) { currentNode = (Element) existingNodeList.item(0); // only the first // one } if (generateId) { // using jdk UUID as uuid generator... id = UUID.randomUUID().toString(); elementRoot.setAttribute("id", id); } currentNode.appendChild(finalDom.importNode(elementRoot, true)); /* * for(int i = 0; i < el; i++){ Node c = existingNodeList.item(i); * * if (generateId) { // using jdk UUID as uuid generator... String id = * UUID.randomUUID().toString(); * * elementRoot.setAttribute("id", id); } * * c.appendChild(finalDom.importNode(elementRoot, true)); * * } */ logger.trace(DomUtils.elementToString(finalDom)); Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("elementXml", DomUtils.elementToString(elementDom)); resultMap.put("elementId", id); return resultMap; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public synchronized Map<String, Object> addElementByPath(final String path, final String originalXml, final String elementXml, boolean generateId) throws SAXException, IOException { Assert.hasText(path);//from ww w . j a va 2 s . c om Assert.hasText(originalXml); Assert.hasText(elementXml); logger.debug(elementXml); Document originalDom = parse(originalXml); Document elementDom = parse(elementXml); Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element elementRoot = (Element) elementDom.getFirstChild(); List<String> nodeList = getNodeList(path); logger.trace("nodeList: " + nodeList + " =? "); Assert.isTrue(nodeList.size() > 0); // remove first one, should be protocol nodeList.remove(0); String newElementName = nodeList.get(nodeList.size() - 1); logger.trace("adding <" + newElementName + ">"); // remove last one, should be <drug>, we are attaching the drug into // drugs... so we want the rightmost element to be drugs... nodeList.remove(nodeList.size() - 1); Element currentNode = finalDomRoot; int c = 0; for (String n : nodeList) { NodeList cur = currentNode.getElementsByTagName(n); String curName = currentNode.getNodeName(); c = cur.getLength(); if (c > 1) { throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n); } if (c == 0) { logger.debug("empty node...; " + n + " doesn't exist under " + curName); Element newN = finalDom.createElement(n); currentNode.appendChild(newN); currentNode = newN; continue; } currentNode = (Element) cur.item(0); } logger.trace("rightmost element: " + currentNode.getNodeName()); String id = ""; if (generateId) { // using jdk UUID as uuid generator... id = UUID.randomUUID().toString(); Assert.isTrue(newElementName.equals(elementRoot.getNodeName()), "the element you are adding does not match the rightmost element name in the path!"); elementRoot.setAttribute("id", id); } currentNode.appendChild(finalDom.importNode(elementRoot, true)); Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("elementXml", DomUtils.elementToString(elementDom)); resultMap.put("elementId", id); return resultMap; }
From source file:com.enonic.vertical.adminweb.PageTemplateHandlerServlet.java
public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems) throws VerticalAdminException { try {// w w w .j av a 2s . co m User user = securityService.getLoggedInAdminConsoleUser(); boolean createPageTemplate; boolean updateStyleSheet = formItems.getBoolean("updatestylesheet", true); boolean updateCSS = formItems.getBoolean("updatecss", false); String xmlData; Document doc; String cssStylesheetKey = null; String datasourcesXML; int menuKey = formItems.getInt("menukey"); ResourceKey stylesheetKey = null; ResourceFile stylesheet = null; ResourceKey cssKey = null; boolean stylesheetValid = false; String cssKeyParam = request.getParameter("selectedcsskey"); if (cssKeyParam != null && !"".equals(cssKeyParam)) { cssKey = new ResourceKey(cssKeyParam); } if (request.getParameter("selstylesheetkey") != null && request.getParameter("selstylesheetkey").length() > 0) { stylesheetKey = new ResourceKey(request.getParameter("selstylesheetkey")); formItems.putString("stylesheetkey", stylesheetKey.toString()); } int key = formItems.getInt("key", -1); // If we have not selected a stylesheet yet if (stylesheetKey == null && cssKey == null && key == -1) { createPageTemplate = true; doc = XMLTool.createDocument("pagetemplates"); Document dsDoc = XMLTool.createDocument("datasources"); datasourcesXML = XMLTool.documentToString(dsDoc); } else { createPageTemplate = (key == -1); int pageTemplateKey; if (stylesheetKey == null && cssKey == null) // createPageTemplate = false { // If we are editing an existing template pageTemplateKey = Integer.parseInt(request.getParameter("key")); xmlData = admin.getPageTemplate(pageTemplateKey); doc = XMLTool.domparse(xmlData); Element pagetemplateElem = XMLTool.getElement(doc.getDocumentElement(), "pagetemplate"); Element stylesheetElem = XMLTool.getElement(pagetemplateElem, "stylesheet"); stylesheetKey = new ResourceKey(stylesheetElem.getAttribute("stylesheetkey")); } else { // If we are making a new template doc = buildPageTemplateXML(formItems, key == -1); Element oldRoot = doc.getDocumentElement(); String keyStr = oldRoot.getAttribute("key"); if (keyStr != null && keyStr.length() > 0) { pageTemplateKey = Integer.parseInt(keyStr); } else { pageTemplateKey = -1; } Element newRoot = XMLTool.createElement(doc, "pagetemplates"); doc.replaceChild(newRoot, oldRoot); newRoot.appendChild(oldRoot); updateStyleSheet = stylesheetKey != null; if (!updateStyleSheet) { Element elem = XMLTool.getElement(oldRoot, "stylesheet"); String styleSheetKeyStr = elem.getAttribute("stylesheetkey"); if (styleSheetKeyStr.length() > 0) { stylesheetKey = new ResourceKey(styleSheetKeyStr); } } } Element cssElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/css"); if (cssElem != null) { if (updateCSS && cssKey == null) { cssElem.getParentNode().removeChild(cssElem); } else { cssStylesheetKey = cssElem.getAttribute("stylesheetkey"); } } Element ptdElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/pagetemplatedata"); Element dselem = XMLTool.getElement(ptdElem, "datasources"); if (dselem != null) { Document dsDoc = XMLTool.createDocument(); dsDoc.appendChild(dsDoc.importNode(dselem, true)); datasourcesXML = XMLTool.documentToString(dsDoc); } else { Document dsDoc = XMLTool.createDocument("datasources"); datasourcesXML = XMLTool.documentToString(dsDoc); } if (!updateStyleSheet) { // Insert valuename attributes all parameters Element[] pagetemplateparamElems = XMLTool.getElements(ptdElem, "pagetemplateparameter"); for (Element pagetemplateparamElem : pagetemplateparamElems) { String keyStr = pagetemplateparamElem.getAttribute("value"); if (keyStr != null && keyStr.length() > 0) { String type = pagetemplateparamElem.getAttribute("type"); if ("category".equals(type)) { int categoryKey = Integer.parseInt(keyStr); String name = admin.getCategoryName(categoryKey); pagetemplateparamElem.setAttribute("valuename", name); } else if ("page".equals(type)) { int menuItemKey = Integer.parseInt(keyStr); String name = admin.getMenuItemName(menuItemKey); pagetemplateparamElem.setAttribute("valuename", name); } else if ("resource".equals(type)) { pagetemplateparamElem.setAttribute("valuename", keyStr); } } } } String menuItemsXML = admin.getMenuItemsByPageTemplates(user, new int[] { pageTemplateKey }); Document menuItemsDoc = XMLTool.domparse(menuItemsXML); XMLTool.mergeDocuments(doc, menuItemsDoc, true); } if (stylesheetKey != null && ((createPageTemplate && cssKey == null) || updateStyleSheet)) { Map<String, Element> elemMap = new HashMap<String, Element>(); Element root = doc.getDocumentElement(); if (updateStyleSheet) { // Remove all parameters from xml root = XMLTool.getElement(root, "pagetemplate"); Element pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplateparameters"); Element[] pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement, "pagetemplateparameter"); for (Element elem : pageTemplateParameterElems) { String name = XMLTool.getElementText(XMLTool.getElement(elem, "name")); elemMap.put(name, elem); } root.removeChild(pageTemplateParamterRootElement); pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplatedata"); pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement, "pagetemplateparameter"); for (Element elem1 : pageTemplateParameterElems) { String name = elem1.getAttribute("name"); elemMap.put(name, elem1); pageTemplateParamterRootElement.removeChild(elem1); } } Element stylesheetParams = XMLTool.createElement(doc, root, "pagetemplateparameters"); Element pagetemplatedataElem = XMLTool.getElement(root, "pagetemplatedata"); if (pagetemplatedataElem == null) { pagetemplatedataElem = XMLTool.createElement(doc, root, "pagetemplatedata"); } stylesheet = resourceService.getResourceFile(stylesheetKey); if (stylesheet != null) { Document stylesheetDoc = null; try { stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument(); stylesheetValid = true; } catch (XMLException e) { } if (stylesheetDoc != null) { Element[] paramElems = XMLTool.getElements(stylesheetDoc.getDocumentElement(), "xsl:param"); for (Element paramElem : paramElems) { Element typeElem = XMLTool.getElement(paramElem, "type"); Element tempElem; String name = paramElem.getAttribute("name"); if (typeElem != null) { String type = XMLTool.getElementText(typeElem); if ("object".equals(type) || "region".equals(type)) { Element elem = elemMap.get(name); if (elem != null && elem.getAttribute("type").length() == 0) { stylesheetParams.appendChild(elem); } else { tempElem = XMLTool.createElement(doc, stylesheetParams, "pagetemplateparameter"); XMLTool.createElement(doc, tempElem, "name", name); } } else { if (elemMap.containsKey(name)) { Element elem = elemMap.get(name); String elemType = elem.getAttribute("type"); if (elemType.length() == 0) { elem.setAttribute("name", name); XMLTool.removeChildNodes(elem, true); } elem.setAttribute("type", type); pagetemplatedataElem.appendChild(elem); } else { tempElem = XMLTool.createElement(doc, pagetemplatedataElem, "pagetemplateparameter"); tempElem.setAttribute("name", name); tempElem.setAttribute("type", type); } } } else { // Alle vanlige parametere, spesifisert som as="xs:string", e.l. i XSL'en. if (elemMap.containsKey(name)) { Element elem = elemMap.get(name); String type = elem.getAttribute("type"); if (type.length() == 0) { elem.setAttribute("name", name); XMLTool.removeChildNodes(elem, true); } else { elem.removeAttribute("type"); elem.removeAttribute("valuename"); } pagetemplatedataElem.appendChild(elem); } else { tempElem = XMLTool.createElement(doc, pagetemplatedataElem, "pagetemplateparameter"); tempElem.setAttribute("name", name); } } } } } } if (stylesheet == null && stylesheetKey != null) { stylesheet = resourceService.getResourceFile(stylesheetKey); } if (stylesheet != null) { Document stylesheetDoc = null; try { stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument(); stylesheetValid = true; } catch (XMLException e) { } if (stylesheetDoc != null) { Element tmpElem = XMLTool.createElement(doc.getDocumentElement(), "resource"); tmpElem.appendChild(doc.importNode(stylesheetDoc.getDocumentElement(), true)); } } // Get content types for this site XMLTool.mergeDocuments(doc, admin.getContentTypes(false).getAsDOMDocument(), true); DOMSource xmlSource = new DOMSource(doc); Source xslSource = AdminStore.getStylesheet(session, "pagetemplate_form.xsl"); HashMap<String, Object> parameters = new HashMap<String, Object>(); addCommonParameters(admin, user, request, parameters, -1, menuKey); if (cssStylesheetKey != null) { parameters.put("cssStylesheetKey", cssStylesheetKey); parameters.put("cssStylesheetExist", resourceService.getResourceFile(new ResourceKey(cssStylesheetKey)) == null ? "false" : "true"); } ResourceKey defaultCSSKey = admin.getDefaultCSSByMenu(menuKey); if (defaultCSSKey != null) { parameters.put("defaultcsskey", defaultCSSKey.toString()); parameters.put("defaultcssExist", resourceService.getResourceFile(defaultCSSKey) == null ? "false" : "true"); } if (createPageTemplate) { parameters.put("create", "1"); } else { parameters.put("create", "0"); } parameters.put("page", String.valueOf(request.getParameter("page"))); datasourcesXML = StringUtil.formatXML(datasourcesXML, 2); parameters.put("datasources", datasourcesXML); parameters.put("menukey", formItems.getString("menukey")); parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", "none")); if (stylesheetKey != null) { parameters.put("selstylesheetkey", stylesheetKey.toString()); parameters.put("selstylesheetExist", stylesheet == null ? "false" : "true"); parameters.put("selstylesheetValid", stylesheetValid ? "true" : "false"); } addAccessLevelParameters(user, parameters); UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser(); String defaultRunAsUserName = "NA"; if (defaultRunAsUser != null) { defaultRunAsUserName = defaultRunAsUser.getDisplayName(); } parameters.put("defaultRunAsUser", defaultRunAsUserName); transformXML(session, response.getWriter(), xmlSource, xslSource, parameters); } catch (TransformerException e) { VerticalAdminLogger.errorAdmin(this.getClass(), 10, "XSLT error: %t", e); } catch (IOException e) { VerticalAdminLogger.errorAdmin(this.getClass(), 20, "I/O error: %t", e); } }
From source file:fi.csc.kapaVirtaAS.MessageTransformer.java
public String transform(String message, MessageDirection direction) throws Exception { try {/*from w ww . j a va2 s .c om*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes()))); doc.setXmlVersion("1.0"); doc.normalizeDocument(); Element root = doc.getDocumentElement(); if (direction == MessageDirection.XRoadToVirta) { // Save XRoad schema prefix for response message xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase())) .findFirst() .orElseThrow( () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found")) .getNodeName(); xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node.getNodeValue().toLowerCase() .contains(conf.getXroadIdSchema().toLowerCase())) .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR, "XroadId schema prefix not found")) .getNodeName(); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema())); //There should be two children under the root node: header and body for (int i = 0; i < root.getChildNodes().getLength(); ++i) { Node child = root.getChildNodes().item(i); // Save soap-headers for reply message and remove child elements under soap-headers if (child.getNodeName().toLowerCase().contains("header")) { this.xroadHeaderElement = child.cloneNode(true); root.replaceChild(child.cloneNode(false), child); } // Change SOAP-body else if (child.getNodeName().toLowerCase().contains("body")) { for (int j = 0; j < child.getChildNodes().getLength(); ++j) { if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) { doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(), child.getChildNodes().item(j).getNodeName() + "Request"); break; } } } } } if (direction == MessageDirection.VirtaToXRoad) { // Add XRoad schemas with saved prefix to response message root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema()); root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema()); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema())); // Change SOAP-headers Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get(); for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) { headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true)); } // Change SOAP-body getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix)) .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix, conf.getAdapterServiceSchema())); //Virta gives malformed soap fault message. Need to parse it correct. getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map( nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault") .map(faultNode -> removeAttribureFromElement( nodeToElement(nodeToElement(faultNode) .getElementsByTagName("faultstring").item(0)), "xml:lang"))); } doc.normalizeDocument(); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(domSource, result); message = writer.toString(); return stripXmlDefinition(message); } catch (Exception e) { if (direction == MessageDirection.XRoadToVirta) { log.error("Error in parsing request message."); throw e; } else { log.error("Error in parsing response message"); log.error(e.toString()); return stripXmlDefinition(faultMessageService.generateSOAPFault(message, faultMessageService.getResValidFail(), this.xroadHeaderElement)); } } }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * /*w w w . j ava 2 s . com*/ * @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); logger.info("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); logger.info("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 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()); } 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:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java
protected final void buildRelatedContentsXML(AdminService admin, User user, ExtendedMap formItems, Element contentsElem) {/*from w w w .jav a 2 s. co m*/ Document doc = contentsElem.getOwnerDocument(); Element contentElem = XMLTool.getFirstElement(contentsElem); Element relatedcontentkeysElem = XMLTool.createElement(doc, contentElem, "relatedcontentkeys"); Element relatedcontentsElem = XMLTool.createElement(doc, contentsElem, "relatedcontents"); int[] relatedContentKeys = contentXMLBuilder.getRelatedContentKeys(formItems); if (relatedContentKeys != null && relatedContentKeys.length > 0) { for (int relatedContentKey : relatedContentKeys) { Element elem = XMLTool.createElement(doc, relatedcontentkeysElem, "relatedcontentkey"); elem.setAttribute("key", Integer.toString(relatedContentKey)); elem.setAttribute("level", "1"); // add related content Document tempDoc = XMLTool.domparse(admin.getContent(user, relatedContentKey, 0, 0, 0)); relatedcontentsElem.appendChild(doc.importNode(tempDoc.getDocumentElement().getFirstChild(), true)); } } }