List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:jef.tools.XMLUtils.java
/** * ??Document?<br/>/*from w w w . ja v a 2s .c o m*/ * ???Document? * * @param parent * * @param nodes * ??? */ public static void appendChild(Node parent, Node... nodes) { Document doc = parent.getOwnerDocument(); for (Node node : nodes) { if (node.getOwnerDocument() != doc) { parent.appendChild(doc.importNode(node, true)); } else { parent.appendChild(node); } } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
/** * Update the pagetemplate in the database. * * @param doc The pagetemplate XML document. * @throws VerticalUpdateException Indicates that the update was not successfull. *//*ww w.j av a2 s . c o m*/ private void updatePageTemplate(Document doc) throws VerticalUpdateException { Element docElem = doc.getDocumentElement(); Element[] pagetemplateElems; if ("pagetemplate".equals(docElem.getTagName())) { pagetemplateElems = new Element[] { docElem }; } else { pagetemplateElems = XMLTool.getElements(doc.getDocumentElement()); } Connection con = null; PreparedStatement preparedStmt = null; int pageTemplateKey; try { con = getConnection(); preparedStmt = con.prepareStatement(PAT_UPDATE); for (Element root : pagetemplateElems) { Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes()); // attribute: key String tmp = root.getAttribute("key"); pageTemplateKey = Integer.parseInt(tmp); preparedStmt.setInt(9, pageTemplateKey); // attribute: type PageTemplateType pageTemplateType = PageTemplateType .valueOf(root.getAttribute("type").toUpperCase()); preparedStmt.setInt(7, pageTemplateType.getKey()); RunAsType runAs = RunAsType.INHERIT; String runAsStr = root.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(8, runAs.getKey()); // attribute: menukey tmp = root.getAttribute("menukey"); int menuKey = Integer.parseInt(tmp); preparedStmt.setInt(2, menuKey); // element: stylesheet Element stylesheet = subelems.get("stylesheet"); String styleSheetKey = stylesheet.getAttribute("stylesheetkey"); preparedStmt.setString(1, styleSheetKey); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setString(3, name); subelem = subelems.get("description"); if (subelem != null) { String description = XMLTool.getElementText(subelem); if (description != null) { preparedStmt.setString(4, description); } else { preparedStmt.setNull(4, Types.VARCHAR); } } else { preparedStmt.setNull(4, Types.VARCHAR); } // element: timestamp (using the database timestamp at creation) /* no code */ // element: contenttypes subelem = subelems.get("contenttypes"); Element[] ctyElems = XMLTool.getElements(subelem); int[] ctys = new int[ctyElems.length]; for (int j = 0; j < ctyElems.length; j++) { ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key")); } setPageTemplateContentTypes(pageTemplateKey, ctys); // element: datasources subelem = subelems.get("pagetemplatedata"); Document ptdDoc = XMLTool.createDocument(); ptdDoc.appendChild(ptdDoc.importNode(subelem, true)); byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8"); ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes); preparedStmt.setBinaryStream(5, byteStream, ptdBytes.length); // element: CSS subelem = subelems.get("css"); if (subelem != null) { String foo = subelem.getAttribute("stylesheetkey"); preparedStmt.setString(6, foo); } else { preparedStmt.setNull(6, Types.VARCHAR); } int result = preparedStmt.executeUpdate(); if (result <= 0) { String message = "Failed to update page template. No page template updated."; VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null); } // If page template is of type "section", we need to create sections for menuitems // that does not have one if (pageTemplateType == PageTemplateType.SECTIONPAGE) { int[] menuItemKeys = getMenuItemKeysByPageTemplate(pageTemplateKey); for (int menuItemKey : menuItemKeys) { MenuItemKey sectionKey = getSectionHandler() .getSectionKeyByMenuItem(new MenuItemKey(menuItemKey)); if (sectionKey == null) { getSectionHandler().createSection(menuItemKey, true, ctys); } } } Element contentobjects = XMLTool.getElement(root, "contentobjects"); Element ptp = XMLTool.getElement(root, "pagetemplateparameters"); if (ptp != null) { int[] paramKeys = new int[0]; // update all ptp entries for page try { int[] oldPTPKey = getPageTemplParamKeys(pageTemplateKey); Node[] ptpNode = XMLTool.filterNodes(ptp.getChildNodes(), Node.ELEMENT_NODE); int[] updatedPTPKey = new int[ptpNode.length]; int updatedPTPs = 0, newPTPs = 0; Document updatedPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element updatedPTP = updatedPTPDoc.getDocumentElement(); Document newPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element newPTP = newPTPDoc.getDocumentElement(); for (Node aPtpNode : ptpNode) { ptp = (Element) aPtpNode; String keyStr = ptp.getAttribute("key"); int key; if (keyStr != null && keyStr.length() > 0) { key = Integer.parseInt(keyStr); } else { key = -1; } if (key >= 0) { updatedPTP.appendChild(updatedPTPDoc.importNode(ptp, true)); updatedPTPKey[updatedPTPs++] = key; } else { newPTP.appendChild(newPTPDoc.importNode(ptp, true)); newPTPs++; } } // remove old if (updatedPTPs == 0) { PageHandler pageHandler = getPageHandler(); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, null); } removePageTemplateCOs(pageTemplateKey, null); removePageTemplParams(pageTemplateKey); } else if (updatedPTPs < oldPTPKey.length) { int temp1[] = new int[updatedPTPs]; System.arraycopy(updatedPTPKey, 0, temp1, 0, updatedPTPs); updatedPTPKey = temp1; Arrays.sort(oldPTPKey); oldPTPKey = ArrayUtil.removeDuplicates(oldPTPKey); Arrays.sort(updatedPTPKey); updatedPTPKey = ArrayUtil.removeDuplicates(updatedPTPKey); int temp2[][] = ArrayUtil.diff(oldPTPKey, updatedPTPKey); PageHandler pageHandler = getPageHandler(); int[] contentObjectKeys = pageHandler.getContentObjectKeys(temp2[0]); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); if (contentObjectKeys != null && contentObjectKeys.length > 0) { for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, contentObjectKeys); } } removePageTemplateCOs(pageTemplateKey, temp2[0]); removePageTemplParams(temp2[0]); } updatePageTemplParam(updatedPTPDoc); if (newPTPs > 0) { paramKeys = createPageTemplParam(null, newPTPDoc); } } catch (VerticalRemoveException vre) { String message = "Failed to remove old page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 3, message, vre); } catch (VerticalCreateException vce) { String message = "Failed to create new page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 4, message, vce); } if (contentobjects != null) { // update all pageconobj entries for page try { Document cobsDoc = XMLTool.createDocument(); cobsDoc.appendChild(cobsDoc.importNode(contentobjects, true)); updatePageTemplateCOs(cobsDoc, pageTemplateKey, paramKeys); } catch (VerticalCreateException vce) { String message = "Failed to create new link from page template to content objects: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 2, message, vce); } } } } } catch (SQLException sqle) { String message = "Failed to update page template because of database error: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 5, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, nfe); } catch (VerticalCreateException vce) { String message = "Failed to create sections for page template: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, vce); } finally { close(preparedStmt); close(con); } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
private int[] createPageTemplate(CopyContext copyContext, Document doc, boolean useOldKey) throws VerticalCreateException { Element docElem = doc.getDocumentElement(); Element[] pagetemplateElems;// w w w . jav a 2s .c o m if ("pagetemplate".equals(docElem.getTagName())) { pagetemplateElems = new Element[] { docElem }; } else { pagetemplateElems = XMLTool.getElements(doc.getDocumentElement()); } Connection con = null; PreparedStatement preparedStmt = null; TIntArrayList newKeys = new TIntArrayList(); try { con = getConnection(); preparedStmt = con.prepareStatement(PAT_CREATE); for (Element root : pagetemplateElems) { Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes()); // key int key; String keyStr = root.getAttribute("key"); if (!useOldKey || keyStr == null || keyStr.length() == 0) { key = getNextKey(PAT_TABLE); } else { key = Integer.parseInt(keyStr); } if (copyContext != null) { copyContext.putPageTemplateKey(Integer.parseInt(keyStr), key); } newKeys.add(key); preparedStmt.setInt(1, key); // attribute: menukey keyStr = root.getAttribute("menukey"); int menuKey = Integer.parseInt(keyStr); preparedStmt.setInt(3, menuKey); // element: stylesheet Element stylesheet = subelems.get("stylesheet"); String tmp = stylesheet.getAttribute("stylesheetkey"); preparedStmt.setString(2, tmp); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setString(4, name); // element: name subelem = subelems.get("description"); if (subelem != null) { String description = XMLTool.getElementText(subelem); if (description != null) { preparedStmt.setString(5, description); } else { preparedStmt.setNull(5, Types.VARCHAR); } } else { preparedStmt.setNull(5, Types.VARCHAR); } // element: timestamp (using the database timestamp at creation) /* no code */ // element: datasources subelem = subelems.get("pagetemplatedata"); Document ptdDoc; if (subelem != null) { ptdDoc = XMLTool.createDocument(); ptdDoc.appendChild(ptdDoc.importNode(subelem, true)); } else { ptdDoc = XMLTool.createDocument("pagetemplatedata"); } byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8"); ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes); preparedStmt.setBinaryStream(6, byteStream, ptdBytes.length); // element: CSS subelem = subelems.get("css"); if (subelem != null) { preparedStmt.setString(7, subelem.getAttribute("stylesheetkey")); } else { preparedStmt.setNull(7, Types.VARCHAR); } // pagetemplate type: PageTemplateType type = PageTemplateType.valueOf(root.getAttribute("type").toUpperCase()); preparedStmt.setInt(8, type.getKey()); RunAsType runAs = RunAsType.INHERIT; String runAsStr = root.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(9, runAs.getKey()); // add int result = preparedStmt.executeUpdate(); if (result == 0) { String message = "Failed to create page template. No page template created."; VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null); } // create page template parameters Element ptpsElem = XMLTool.getElement(root, "pagetemplateparameters"); int[] ptpKeys = null; if (ptpsElem != null) { Element[] ptpElems = XMLTool.getElements(ptpsElem); for (Element ptpElem : ptpElems) { ptpElem.setAttribute("pagetemplatekey", Integer.toString(key)); } Document ptpDoc = XMLTool.createDocument(); Node n = ptpDoc.importNode(ptpsElem, true); ptpDoc.appendChild(n); ptpKeys = createPageTemplParam(copyContext, ptpDoc); } // create all pageconobj entries for page Element contentobjectsElem = XMLTool.getElement(root, "contentobjects"); if (contentobjectsElem != null) { Element[] contentobjectElems = XMLTool.getElements(contentobjectsElem); for (Element contentobjectElem : contentobjectElems) { contentobjectElem.setAttribute("pagetemplatekey", Integer.toString(key)); if (copyContext != null) { keyStr = contentobjectElem.getAttribute("parameterkey"); int newKey = copyContext.getPageTemplateParameterKey(Integer.parseInt(keyStr)); contentobjectElem.setAttribute("parameterkey", String.valueOf(newKey)); } else { int pIndex = Integer .parseInt(contentobjectElem.getAttribute("parameterkey").substring(1)); contentobjectElem.setAttribute("parameterkey", Integer.toString(ptpKeys[pIndex])); } } Document coDoc = XMLTool.createDocument(); coDoc.appendChild(coDoc.importNode(contentobjectsElem, true)); updatePageTemplateCOs(coDoc, key, ptpKeys); } // element: contenttypes subelem = subelems.get("contenttypes"); Element[] ctyElems = XMLTool.getElements(subelem); int[] ctys = new int[ctyElems.length]; for (int j = 0; j < ctyElems.length; j++) { ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key")); } setPageTemplateContentTypes(key, ctys); } } catch (SQLException sqle) { String message = "Failed to create page template because of database error: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 1, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 2, message, nfe); } catch (VerticalKeyException gke) { String message = "Failed generate page template key: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 3, message, gke); } finally { close(preparedStmt); close(con); } return newKeys.toArray(); }
From source file:com.enonic.vertical.userservices.FormHandlerController.java
@Override protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem, ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException { int menuItemKey = formItems.getInt("_form_id"); // Elements in the old form XML are prefixed with an underscore Element _formElement = (Element) formItems.get("__form"); Document doc = contentdataElem.getOwnerDocument(); Element formElement = XMLTool.createElement(doc, contentdataElem, "form"); formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey")); // Set title element: Element _titleElement = XMLTool.getElement(_formElement, "title"); XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement)); // There may be multiple error states/codes, so we have to keep track of them. // When errors occurr, XML is inserted into the resulting document, and sent // back to the user client. // TIntArrayList errorCodes = new TIntArrayList(5); List<Integer> errorCodes = new ArrayList<Integer>(5); // The people that will recieve the form mail: Element recipientsElem = XMLTool.getElement(_formElement, "recipients"); if (recipientsElem != null) { formElement.appendChild(doc.importNode(recipientsElem, true)); }//from w w w .ja va 2 s. co m // Loop all form items and insert the data from the form: int fileattachmentCount = 0; Element[] _formItems = XMLTool.getElements(_formElement, "item"); for (int i = 0; i < _formItems.length; i++) { String formName = menuItemKey + "_form_" + (i + 1); Element itemElement = (Element) doc.importNode(_formItems[i], true); formElement.appendChild(itemElement); String type = itemElement.getAttribute("type"); if ("text".equals(type)) { // Remove default data: Element tmpElement = XMLTool.getElement(itemElement, "data"); if (tmpElement != null) { itemElement.removeChild(tmpElement); } } if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) { String value = formItems.getString(formName, ""); // If a regular expression is specified, it should be verified that // the data entered in the form conforms to this: String regexp = itemElement.getAttribute("validation"); if ("text".equals(type) && regexp != null && regexp.length() > 0) { final boolean valueIsNonEmpty = value.length() > 0; if (!value.matches(regexp) && valueIsNonEmpty) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED) .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED)); if (!errorCodes.contains(ERR_VALIDATION_FAILED)) { errorCodes.add(ERR_VALIDATION_FAILED); } } } // If the form element is required, we must test that the user actually // entered data: if (itemElement.getAttribute("required").equals("true") && value.length() == 0) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } XMLTool.createElement(doc, itemElement, "data", value); } else if ("checkbox".equals(type)) { String value; if (formItems.getString(formName, "").equals("on")) { value = "1"; } else { value = "0"; } XMLTool.createElement(doc, itemElement, "data", value); } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) { String value = formItems.getString(formName, null); boolean selected = false; Element tmpElement = XMLTool.getElement(itemElement, "data"); Element[] options = XMLTool.getElements(tmpElement, "option"); for (Element option : options) { tmpElement = option; if (tmpElement.getAttribute("value").equals(value)) { tmpElement.setAttribute("selected", "true"); selected = true; break; } } // If the form element is required, we must test that the user actually // checked on of the radiobuttons: if (itemElement.getAttribute("required").equals("true") && !selected) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } } else if ("checkboxes".equals(type)) { String[] values = formItems.getStringArray(formName); Element tmpElement = XMLTool.getElement(itemElement, "data"); Element[] options = XMLTool.getElements(tmpElement, "option"); for (Element option : options) { tmpElement = option; for (String currentValue : values) { if (tmpElement.getAttribute("value").equals(currentValue)) { tmpElement.setAttribute("selected", "true"); break; } } } } else if ("fileattachment".equals(type)) { FileItem fileItem = formItems.getFileItem(formName, null); // If the form element is required, we must test that the user actually // entered data: if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } else if (fileItem != null) { String fileName = FileUtil.getFileName(fileItem); Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName); binaryDataElem.setAttribute("key", "%" + fileattachmentCount++); } } } HttpServletRequest request = ServletRequestAccessor.getRequest(); try { Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create"); if ((captchaOk != null) && (!captchaOk)) { errorCodes.add(ERR_INVALID_CAPTCHA); } } catch (CaptchaServiceException e) { String message = "Failed during captcha validation: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, e); errorCodes.add(ERR_OPERATION_BACKEND); } // If one or more errors occurred, an exception is thrown, containing the errorcodes // and the resulting document (that now should include error XML): if (errorCodes.size() > 0) { throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()])); } VerticalUserServicesLogger.debug(this.getClass(), 10, doc); }
From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java
private Element feed(final AtomFeed feed) throws ParserConfigurationException { final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED); feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM); feedElem.setAttribute(ODataConstants.XMLNS_METADATA, client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA)); feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES)); feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML); feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS); if (feed.getBaseURI() != null) { feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString()); }/*from w w w .j ava2 s .c om*/ doc.appendChild(feedElem); if (StringUtils.isNotBlank(feed.getTitle())) { final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE); title.appendChild(doc.createTextNode(feed.getTitle())); feedElem.appendChild(title); } if (StringUtils.isNotBlank(feed.getSummary())) { final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY); summary.appendChild(doc.createTextNode(feed.getSummary())); feedElem.appendChild(summary); } for (AtomEntry entry : feed.getEntries()) { feedElem.appendChild(doc.importNode(entry(entry), true)); } return feedElem; }
From source file:com.msopentech.odatajclient.engine.data.atom.AtomSerializer.java
private static Element entry(final AtomEntry entry) throws ParserConfigurationException { final DocumentBuilder builder = ODataConstants.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, ODataConstants.NS_METADATA); entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.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()); }/*from ww w . j ava 2 s. c o m*/ 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, ODataConstants.ATOM_CATEGORY_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:com.enonic.cms.web.portal.services.FormServicesProcessor.java
@Override protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem, ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException { int menuItemKey = formItems.getInt("_form_id"); // Elements in the old form XML are prefixed with an underscore Element _formElement = (Element) formItems.get("__form"); Document doc = contentdataElem.getOwnerDocument(); Element formElement = XMLTool.createElement(doc, contentdataElem, "form"); formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey")); // Set title element: Element _titleElement = XMLTool.getElement(_formElement, "title"); XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement)); // There may be multiple error states/codes, so we have to keep track of them. // When errors occurr, XML is inserted into the resulting document, and sent // back to the user client. // TIntArrayList errorCodes = new TIntArrayList(5); List<Integer> errorCodes = new ArrayList<Integer>(5); // The people that will recieve the form mail: Element recipientsElem = XMLTool.getElement(_formElement, "recipients"); if (recipientsElem != null) { formElement.appendChild(doc.importNode(recipientsElem, true)); }//from w w w . j av a 2 s .c o m // Loop all form items and insert the data from the form: int fileattachmentCount = 0; Element[] _formItems = XMLTool.getElements(_formElement, "item"); for (int i = 0; i < _formItems.length; i++) { String formName = menuItemKey + "_form_" + (i + 1); Element itemElement = (Element) doc.importNode(_formItems[i], true); formElement.appendChild(itemElement); String type = itemElement.getAttribute("type"); if ("text".equals(type)) { // Remove default data: Element tmpElement = XMLTool.getElement(itemElement, "data"); if (tmpElement != null) { itemElement.removeChild(tmpElement); } } if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) { String value = formItems.getString(formName, ""); // If a regular expression is specified, it should be verified that // the data entered in the form conforms to this: String regexp = itemElement.getAttribute("validation"); if ("text".equals(type) && regexp != null && regexp.length() > 0) { final boolean valueIsNonEmpty = value.length() > 0; if (!value.matches(regexp) && valueIsNonEmpty) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED) .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED)); if (!errorCodes.contains(ERR_VALIDATION_FAILED)) { errorCodes.add(ERR_VALIDATION_FAILED); } } } // If the form element is required, we must test that the user actually // entered data: if (itemElement.getAttribute("required").equals("true") && value.length() == 0) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } XMLTool.createElement(doc, itemElement, "data", value); } else if ("checkbox".equals(type)) { String value; if (formItems.getString(formName, "").equals("on")) { value = "1"; } else { value = "0"; } XMLTool.createElement(doc, itemElement, "data", value); } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) { String value = formItems.getString(formName, null); boolean selected = false; Element tmpElement = XMLTool.getElement(itemElement, "data"); Element[] options = XMLTool.getElements(tmpElement, "option"); for (Element option : options) { tmpElement = option; if (tmpElement.getAttribute("value").equals(value)) { tmpElement.setAttribute("selected", "true"); selected = true; break; } } // If the form element is required, we must test that the user actually // checked on of the radiobuttons: if (itemElement.getAttribute("required").equals("true") && !selected) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } } else if ("checkboxes".equals(type)) { String[] values = formItems.getStringArray(formName); Element tmpElement = XMLTool.getElement(itemElement, "data"); Element[] options = XMLTool.getElements(tmpElement, "option"); for (Element option : options) { tmpElement = option; for (String currentValue : values) { if (tmpElement.getAttribute("value").equals(currentValue)) { tmpElement.setAttribute("selected", "true"); break; } } } } else if ("fileattachment".equals(type)) { FileItem fileItem = formItems.getFileItem(formName, null); // If the form element is required, we must test that the user actually // entered data: if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) { XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id", String.valueOf(ERR_MISSING_REQ)); if (!errorCodes.contains(ERR_MISSING_REQ)) { errorCodes.add(ERR_MISSING_REQ); } } else if (fileItem != null) { String fileName = FileUtil.getFileName(fileItem); Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName); binaryDataElem.setAttribute("key", "%" + fileattachmentCount++); } } } HttpServletRequest request = ServletRequestAccessor.getRequest(); Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create"); if ((captchaOk != null) && (!captchaOk)) { errorCodes.add(ERR_INVALID_CAPTCHA); } // If one or more errors occurred, an exception is thrown, containing the errorcodes // and the resulting document (that now should include error XML): if (errorCodes.size() > 0) { throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()])); } }
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 ww w . j a va 2 s .c om * <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 authors * @return */ // IMPORTANT!!! Currently not working due to missing userHnadle info public static Node queryCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl = null; try { System.out.println("queryCone: " + model); 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(); 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]; GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO"); logger.info(detailMethod.getPath()); logger.info(detailMethod.getQueryString()); if (coneSession != null) { detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, detailMethod); 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."); logger.debug("Stacktrace", e); return null; //throw new RuntimeException(e); } }
From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java
/** * Adds the new release element to changes.xml document * /*from w w w. j a v a2s . c om*/ * @param changesDocument * @param changesXml * @throws MojoExecutionException */ private void addNewRelease(final Document changesDocument, final byte[] changesXml) throws MojoExecutionException { try { // formamos el documento obtenido final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final ByteArrayInputStream bais = new ByteArrayInputStream(changesXml); final Document docChanges = db.parse(bais); // recuperamos el nodo de la release // slo debe haber un elemento final Node releaseNode = docChanges.getElementsByTagName(ELEMENT_RELEASE).item(0); // lo aadimos al elemento body del que ya tenemos // solo hay un body final Element bodyElement = (Element) changesDocument.getElementsByTagName(ELEMENT_BODY).item(0); final Node importNode = changesDocument.importNode(releaseNode, true); bodyElement.appendChild(importNode); } catch (final ParserConfigurationException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } catch (final SAXException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } catch (final IOException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } }
From source file:cc.siara.csv_ml_demo.MainActivity.java
/** * Evaluates given XPath from Input box against Document generated by * parsing csv_ml in input box and sets value or node list to output box. *///from ww w. ja va 2 s. c o m void processXPath() { EditText etInput = (EditText) findViewById(R.id.etInput); EditText etXPath = (EditText) findViewById(R.id.etXPath); CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty); XPath xpath = XPathFactory.newInstance().newXPath(); MultiLevelCSVParser parser = new MultiLevelCSVParser(); Document doc = null; try { doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false); } catch (IOException e1) { e1.printStackTrace(); } if (doc == null) return; StringBuffer out_str = new StringBuffer(); try { XPathExpression expr = xpath.compile(etXPath.getText().toString()); try { Document outDoc = Util.parseXMLToDOM("<output></output>"); Element rootElement = outDoc.getDocumentElement(); NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < ret.getLength(); i++) { Object o = ret.item(i); if (o instanceof String) { out_str.append(o); } else if (o instanceof Node) { Node n = (Node) o; short nt = n.getNodeType(); switch (nt) { case Node.TEXT_NODE: case Node.ATTRIBUTE_NODE: case Node.CDATA_SECTION_NODE: // Only one value gets // evaluated? if (out_str.length() > 0) out_str.append(','); if (nt == Node.ATTRIBUTE_NODE) out_str.append(n.getNodeValue()); else out_str.append(n.getTextContent()); break; case Node.ELEMENT_NODE: rootElement.appendChild(outDoc.importNode(n, true)); break; } } } if (out_str.length() > 0) { rootElement.setTextContent(out_str.toString()); out_str.setLength(0); } out_str.append(Util.docToString(outDoc, true)); } catch (Exception e) { // Thrown most likely because the given XPath evaluates to a // string out_str.append(expr.evaluate(doc)); } } catch (XPathExpressionException e) { e.printStackTrace(); } if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml")) out_str.delete(0, out_str.indexOf(">") + 1); EditText etOutput = (EditText) findViewById(R.id.etOutput); etOutput.setText(out_str.toString()); // tfOutputSize.setText(String.valueOf(xmlString.length())); }