List of usage examples for org.w3c.dom Node appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:ca.digitalface.jasperoo.JasperooOperationsImpl.java
/** * Sets up the "List" tag./*from www.j a v a2 s . com*/ */ private void setupListTagx() { String docPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/tags/form/list.tagx"); MutableFile mutableDocXml = null; Document targetDoc; try { if (fileManager.exists(docPath)) { mutableDocXml = fileManager.updateFile(docPath); targetDoc = XmlUtils.getDocumentBuilder().parse(mutableDocXml.getInputStream()); } else { throw new IllegalStateException("Could not acquire " + docPath); } } catch (Exception e) { throw new IllegalStateException(e); } Node target = XmlUtils.findFirstElementByName("jsp:doBody", targetDoc.getDocumentElement()).getParentNode(); /* * <c:catch> * <c:if test="${not empty object.reportable}"/> * <spring:message code="jasperoo_reports" htmlEscape="false" var="reports_label"/> * <b><c:out value="${reports_label} "/></b> * </c:if> * </c:catch> */ Element catchNode = new XmlElementBuilder("c:catch", targetDoc).addChild( new XmlElementBuilder("c:if", targetDoc).addAttribute("test", "${not empty items[0].reportable}") .addChild(new XmlElementBuilder("spring:message", targetDoc) .addAttribute("code", "jasperoo_reports").addAttribute("htmlEscape", "false") .addAttribute("var", "reports_label").build()) .addChild(new XmlElementBuilder("b", targetDoc) .addChild(new XmlElementBuilder("c:out", targetDoc) .addAttribute("value", "${reports_label} ").build()) .build()) .build()) .build(); target.appendChild(catchNode); XmlUtils.writeXml(mutableDocXml.getOutputStream(), targetDoc); }
From source file:lcmc.data.VMSXML.java
/** Modify xml of some device element. */ private void modifyXML(final Node domainNode, final String domainName, final Map<String, String> tagMap, final Map<String, String> attributeMap, final Map<String, String> parametersMap, final String path, final String elementName, final VirtualHardwareComparator vhc) { final String configName = namesConfigsMap.get(domainName); if (configName == null) { return;/*from w ww . j av a 2 s . c o m*/ } //final Node domainNode = getDomainNode(domainName); if (domainNode == null) { return; } final XPath xpath = XPathFactory.newInstance().newXPath(); final Node devicesNode = getDevicesNode(xpath, domainNode); if (devicesNode == null) { return; } try { final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET); Element hwNode = vhc.getElement(nodes, parametersMap); if (hwNode == null) { hwNode = (Element) devicesNode .appendChild(domainNode.getOwnerDocument().createElement(elementName)); } for (final String param : parametersMap.keySet()) { final String value = parametersMap.get(param); if (!tagMap.containsKey(param) && attributeMap.containsKey(param)) { /* attribute */ final Node attributeNode = hwNode.getAttributes().getNamedItem(attributeMap.get(param)); if (attributeNode == null) { if (value != null && !"".equals(value)) { hwNode.setAttribute(attributeMap.get(param), value); } } else if (value == null || "".equals(value)) { hwNode.removeAttribute(attributeMap.get(param)); } else { attributeNode.setNodeValue(value); } continue; } Element node = (Element) getChildNode(hwNode, tagMap.get(param)); if ((attributeMap.containsKey(param) || "True".equals(value)) && node == null) { node = (Element) hwNode .appendChild(domainNode.getOwnerDocument().createElement(tagMap.get(param))); } else if (node != null && !attributeMap.containsKey(param) && (value == null || "".equals(value))) { hwNode.removeChild(node); } if (attributeMap.containsKey(param)) { final Node attributeNode = node.getAttributes().getNamedItem(attributeMap.get(param)); if (attributeNode == null) { if (value != null && !"".equals(value)) { node.setAttribute(attributeMap.get(param), value); } } else { if (value == null || "".equals(value)) { node.removeAttribute(attributeMap.get(param)); } else { attributeNode.setNodeValue(value); } } } } final Element hwAddressNode = (Element) getChildNode(hwNode, HW_ADDRESS); if (hwAddressNode != null) { hwNode.removeChild(hwAddressNode); } } catch (final javax.xml.xpath.XPathExpressionException e) { Tools.appError("could not evaluate: ", e); return; } }
From source file:lcmc.data.VMSXML.java
/** Add features. */ private void addFeatures(final Document doc, final Node root, final Map<String, String> parametersMap) { final boolean acpi = "True".equals(parametersMap.get(VM_PARAM_ACPI)); final boolean apic = "True".equals(parametersMap.get(VM_PARAM_APIC)); final boolean pae = "True".equals(parametersMap.get(VM_PARAM_PAE)); final boolean hap = "True".equals(parametersMap.get(VM_PARAM_HAP)); if (acpi || apic || pae || hap) { final Element featuresNode = (Element) root.appendChild(doc.createElement("features")); if (acpi) { featuresNode.appendChild(doc.createElement("acpi")); }/* ww w.j a v a 2 s. c o m*/ if (apic) { featuresNode.appendChild(doc.createElement("apic")); } if (pae) { featuresNode.appendChild(doc.createElement("pae")); } if (hap) { featuresNode.appendChild(doc.createElement("hap")); } } }
From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java
/** * Copy file that will displayed in Jmol * @param doc XML document/*from w w w. j a v a 2s . c o m*/ * @param rootElt Root element * @param xreader XPath reader for the document * @param dataDirPath Path to directory that contains analysis data * @param dirPath Path to experiment directory * @return XML element for Jmol data * @throws IOException */ private Element pullJmolFile(Document doc, Node rootElt, XPathReader xreader, String dataDirPath, String dirPath) throws IOException { Element jmolElt = doc.createElement("jmol"); String mainStructureRelPath = (String) xreader .read("ibiomes/directory/AVUs/AVU[@id='MAIN_3D_STRUCTURE_FILE']", XPathConstants.STRING); if (mainStructureRelPath != null && mainStructureRelPath.length() > 0) { String dataFileNewName = mainStructureRelPath.replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_"); String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName; Files.copy(Paths.get(dirPath + PATH_FOLDER_SEPARATOR + mainStructureRelPath), Paths.get(dataFileDestPath), StandardCopyOption.REPLACE_EXISTING); //set read permissions if (!Utils.isWindows()) { Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>(); permissions.add(PosixFilePermission.OWNER_READ); permissions.add(PosixFilePermission.OWNER_WRITE); permissions.add(PosixFilePermission.OWNER_EXECUTE); permissions.add(PosixFilePermission.GROUP_READ); permissions.add(PosixFilePermission.OTHERS_READ); Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions); } jmolElt.setAttribute("path", dataFileNewName); jmolElt.setAttribute("name", mainStructureRelPath); NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dirPath + PATH_FOLDER_SEPARATOR + mainStructureRelPath + "']/AVUs/AVU", XPathConstants.NODESET); MetadataAVUList avuList = parseMetadata(avuNodes); String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION); if (description != null && description.length() > 0) jmolElt.setAttribute("description", description); rootElt.appendChild(jmolElt); return jmolElt; } else return null; }
From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java
private void menuItemForm(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems) throws VerticalAdminException { int menuKey = formItems.getInt("menukey"); User user = securityService.getLoggedInAdminConsoleUser(); String menuXML = admin.getAdminMenu(user, menuKey); boolean forwardData = formItems.getBoolean("forward_data", false); boolean create; String menuItemXML = null;//from www. j av a 2 s . co m String categoryXML = null; String pageTemplatesXML; String pageTemplateParamsXML = null; String defaultAccessRightXML = null; // menuitem key: String key = formItems.getString("key", null); try { if (key != null && !key.startsWith("f") && !key.equals("none")) { create = false; menuItemXML = admin.getMenuItem(user, Integer.parseInt(key), false, true); } else { create = true; String insertBelow = formItems.getString("insertbelow", null); if (insertBelow != null && !"-1".equals(insertBelow)) { defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM, Integer.parseInt(insertBelow), true); } else { defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM_DEFAULT, menuKey, true); } } int[] excludeTypeKeys = null; // before we excluded page-tempales of type newsletter, but not anymore. pageTemplatesXML = admin.getPageTemplatesByMenu(menuKey, excludeTypeKeys); Document doc1 = XMLTool.domparse(menuXML); Element menuElem = XMLTool.selectElement(doc1.getDocumentElement(), "//menu[@key = '" + menuKey + "']"); int pageTemplateKey = formItems.getInt("selpagetemplatekey", -1); if (pageTemplateKey < 0 && create) { // selpagetemplatekey has not been set... set it to parent or default // pagetemplatekey (if appliccable) int insertBelow = -1; if (formItems.containsKey("insertbelow") /* && formItems.get("insertbelow") instanceof Integer */ ) { insertBelow = formItems.getInt("insertbelow"); } pageTemplateKey = findParentPagetemplateKey(doc1, insertBelow); formItems.putInt("selpagetemplatekey", pageTemplateKey); } if (pageTemplateKey >= 0) { pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } else if (menuItemXML != null && XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey") != null) { pageTemplateKey = Integer.parseInt(XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey")); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } else { String tmp = menuElem.getAttribute("defaultpagetemplate"); if (tmp != null && tmp.length() > 0) { pageTemplateKey = Integer.parseInt(tmp); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } } // insert correct menuitem XML: Element menuitemElem = null; if (menuItemXML != null) { Document miDoc = XMLTool.domparse(menuItemXML); Element tmpElem = miDoc.getDocumentElement(); tmpElem = XMLTool.getFirstElement(tmpElem); if (tmpElem != null) { // add read count // int readCount = admin.getReadCount(LogHandler.TABLE_TMENUITEM, Integer.parseInt(key)); // Element elem = XMLTool.createElement(miDoc, tmpElem, "logentries"); // elem.setAttribute("totalread", String.valueOf(readCount)); if (tmpElem != null) { String xpath = "//menuitem[@key = '" + key + "']"; Element oldElem = (Element) XMLTool.selectNode(doc1.getDocumentElement(), xpath); if (oldElem != null) { Element menuitemsElem = (Element) oldElem.getParentNode(); menuitemElem = (Element) doc1.importNode(tmpElem, true); menuitemsElem.replaceChild(menuitemElem, oldElem); } } } } Document pageTemplateDoc = XMLTool.domparse(pageTemplatesXML); XMLTool.mergeDocuments(doc1, pageTemplateDoc, true); if (defaultAccessRightXML != null) { XMLTool.mergeDocuments(doc1, XMLTool.domparse(defaultAccessRightXML), true); } ExtendedMap parameters = new ExtendedMap(); if (forwardData) { // get accessrights element Node nodeAccessRights; if (create) { nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "/menus/accessrights"); } else { nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "//menuitem[@key=" + key + "]/accessrights"); } // get new accessrights xml from parameters String xmlAccessRights = buildAccessRightsXML(formItems); if (xmlAccessRights != null) { Document docAccessRights = XMLTool.domparse(xmlAccessRights); if (docAccessRights.getDocumentElement().hasChildNodes()) // replace accessrights element with the generated accessrights { nodeAccessRights.getParentNode().replaceChild( doc1.importNode(docAccessRights.getDocumentElement(), true), nodeAccessRights); } } // get custom parameters // get parameters element Node nodeParameters; if (create) { Node nodeMenu = XMLTool.selectNode(doc1.getDocumentElement(), "/menus"); nodeParameters = XMLTool.createElement(doc1, (Element) nodeMenu, "parameters"); nodeMenu.appendChild(nodeParameters); } else { nodeParameters = XMLTool.selectNode(doc1.getDocumentElement(), "//menuitem[@key=" + key + "]/parameters"); } XMLTool.removeChildNodes((Element) nodeParameters, false); if (isArrayFormItem(formItems, "paramname")) { String[] paramName = (String[]) formItems.get("paramname"); String[] paramValue = (String[]) formItems.get("paramval"); for (int i = 0; i < paramName.length; i++) { final String currParamName = paramName[i]; if (currParamName == null || !currParamName.trim().equals("")) { Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter", paramValue[i]); newElem.setAttribute("name", currParamName); nodeParameters.appendChild(newElem); } } } else { // ingen sideparametre finnes, vi lager en String paramName = formItems.getString("paramname", ""); String paramValue = formItems.getString("paramval", ""); if (paramName.length() > 0) { Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter", paramValue); newElem.setAttribute("name", paramName); nodeParameters.appendChild(newElem); } } parameters.put("referer", formItems.getString("referer")); } if (pageTemplateParamsXML == null) { Element nameElem = (Element) XMLTool.selectNode(doc1, "//menuitem[@key = '" + key + "']/page"); if (nameElem != null) { pageTemplateKey = Integer.parseInt(nameElem.getAttribute("pagetemplatekey")); pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey); } } Document doc8; if (pageTemplateParamsXML != null) { doc8 = XMLTool.domparse(pageTemplateParamsXML); XMLTool.mergeDocuments(doc1, doc8, true); } String xpath = "/pagetemplates/pagetemplate[@key=" + pageTemplateKey + "]"; Element pagetemplateElem = (Element) XMLTool.selectNode(pageTemplateDoc, xpath); if (pagetemplateElem != null) { String pageTemplateType = pagetemplateElem.getAttribute("type"); if ("form".equals(pageTemplateType)) { Element dataElem = XMLTool.getElement(menuitemElem, "data"); Element formElem = XMLTool.getElement(dataElem, "form"); if (formElem != null) { String keyStr = formElem.getAttribute("categorykey"); if (keyStr.length() > 0) { int categoryKey = Integer.parseInt(keyStr); categoryXML = admin.getCategoryNameXML(categoryKey); } } } } if (categoryXML != null) { Document doc5 = XMLTool.domparse(categoryXML); XMLTool.mergeDocuments(doc1, doc5, true); } // Get content types for this site XMLTool.mergeDocuments(doc1, admin.getContentTypes(false).getAsDOMDocument(), true); // Append languages Document langs = XMLTool.domparse(admin.getLanguages()); XMLTool.mergeDocuments(doc1, langs, true); DOMSource xmlSource = new DOMSource(doc1); // Stylesheet Source xslSource = AdminStore.getStylesheet(session, "menu_item_form.xsl"); // Parameters addCommonParameters(admin, user, request, parameters, -1, menuKey); parameters.put("page", String.valueOf(request.getParameter("page"))); if ((key == null || key.length() == 0 || key.equals("none"))) { parameters.put("key", "none"); } else { parameters.put("key", key); } String type = formItems.getString("type", null); if ((type == null || "page".equals(type)) && pageTemplateKey >= 0) { if (pagetemplateElem != null) { type = pagetemplateElem.getAttribute("type"); } } if ("document".equals(type) || "form".equals(type)) { type = "content"; } parameters.put("type", type); parameters.put("insertbelow", formItems.getString("insertbelow", null)); parameters.put("selpagetemplatekey", String.valueOf(pageTemplateKey)); parameters.put("name", formItems.getString("name", null)); if ("on".equals(formItems.getString("visibility", null))) { parameters.put("visibility", "on"); } parameters.put("forward_data", formItems.get("forward_data", Boolean.FALSE)); parameters.put("menu-name", formItems.getString("menu-name", null)); parameters.put("displayname", formItems.getString("displayname", null)); parameters.put("description", formItems.getString("description", null)); parameters.put("keywords", formItems.getString("keywords", null)); parameters.put("alias", formItems.getString("alias", null)); parameters.put("document", formItems.getString("contentdata_body", null)); if (formItems.getString("noauth", null) != null) { if ("on".equals(formItems.getString("noauth", null))) { parameters.put("noauth", "false"); } else { parameters.put("noauth", "true"); } } parameters.put("catselkey", formItems.getString("catsel", null)); parameters.put("catkey", formItems.getString("category_key", null)); parameters.put("catname", formItems.getString("viewcategory_key", null)); parameters.put("menukey", String.valueOf(menuKey)); // find content title if contentkey is specified if (menuitemElem != null) { String contentKeyStr = menuitemElem.getAttribute("contentkey"); if (contentKeyStr.length() > 0) { int contentKey = Integer.parseInt(contentKeyStr); int versionKey = admin.getCurrentVersionKey(contentKey); String contentTitle = admin.getContentTitle(versionKey); parameters.put("contenttitle", contentTitle); } } // Adds accessrights values, so that these can be remembered until next page for (Object formItemKey : formItems.keySet()) { String paramName = (String) formItemKey; if (paramName.startsWith("accessright[key=")) { parameters.put(paramName, formItems.getString(paramName)); } } parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", null)); // Get form categories int[] contentTypeKeys = admin.getContentTypesByHandlerClass( "com.enonic.vertical.adminweb.handlers.ContentFormHandlerServlet"); if (contentTypeKeys != null && contentTypeKeys.length > 0) { StringBuffer contentTypeString = new StringBuffer(); for (int i = 0; i < contentTypeKeys.length; i++) { if (i > 0) { contentTypeString.append(','); } contentTypeString.append(contentTypeKeys[i]); } parameters.put("contenttypestring", contentTypeString.toString()); } else { parameters.put("contenttypestring", "99999"); } 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 (IOException ioe) { String msg = "I/O error: %t"; VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, ioe); } catch (TransformerException te) { String msg = "XSL transformer error: %t"; VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, te); } }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
private void saveSecurity(Security security, Document document, Element root) { Element element = document.createElement("security"); //$NON-NLS-1$ element.setAttribute("id", String.valueOf(security.getId())); //$NON-NLS-1$ root.appendChild(element);/* w w w .jav a 2 s. com*/ Element node = document.createElement("code"); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getCode())); element.appendChild(node); node = document.createElement("description"); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getDescription())); element.appendChild(node); if (security.getCurrency() != null) { node = document.createElement("currency"); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getCurrency().getCurrencyCode())); element.appendChild(node); } NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(2); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); Element collectorNode = document.createElement("dataCollector"); //$NON-NLS-1$ collectorNode.setAttribute("enable", String.valueOf(security.isEnableDataCollector())); //$NON-NLS-1$ element.appendChild(collectorNode); node = document.createElement("begin"); //$NON-NLS-1$ node.appendChild(document.createTextNode( nf.format(security.getBeginTime() / 60) + ":" + nf.format(security.getBeginTime() % 60))); //$NON-NLS-1$ collectorNode.appendChild(node); node = document.createElement("end"); //$NON-NLS-1$ node.appendChild(document.createTextNode( nf.format(security.getEndTime() / 60) + ":" + nf.format(security.getEndTime() % 60))); //$NON-NLS-1$ collectorNode.appendChild(node); node = document.createElement("weekdays"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getWeekDays()))); collectorNode.appendChild(node); node = document.createElement("keepdays"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getKeepDays()))); collectorNode.appendChild(node); if (security.getQuoteFeed() != null || security.getLevel2Feed() != null || security.getHistoryFeed() != null) { Node feedsNode = document.createElement("feeds"); //$NON-NLS-1$ element.appendChild(feedsNode); if (security.getQuoteFeed() != null) { node = document.createElement("quote"); //$NON-NLS-1$ node.setAttribute("id", security.getQuoteFeed().getId()); //$NON-NLS-1$ if (security.getQuoteFeed().getExchange() != null) node.setAttribute("exchange", security.getQuoteFeed().getExchange()); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getQuoteFeed().getSymbol())); feedsNode.appendChild(node); } if (security.getLevel2Feed() != null) { node = document.createElement("level2"); //$NON-NLS-1$ node.setAttribute("id", security.getLevel2Feed().getId()); //$NON-NLS-1$ if (security.getLevel2Feed().getExchange() != null) node.setAttribute("exchange", security.getLevel2Feed().getExchange()); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getLevel2Feed().getSymbol())); feedsNode.appendChild(node); } if (security.getHistoryFeed() != null) { node = document.createElement("history"); //$NON-NLS-1$ node.setAttribute("id", security.getHistoryFeed().getId()); //$NON-NLS-1$ if (security.getHistoryFeed().getExchange() != null) node.setAttribute("exchange", security.getHistoryFeed().getExchange()); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getHistoryFeed().getSymbol())); feedsNode.appendChild(node); } } if (security.getTradeSource() != null) { TradeSource source = security.getTradeSource(); Element feedsNode = document.createElement("tradeSource"); //$NON-NLS-1$ feedsNode.setAttribute("id", source.getTradingProviderId()); //$NON-NLS-1$ if (source.getExchange() != null) feedsNode.setAttribute("exchange", source.getExchange()); //$NON-NLS-1$ element.appendChild(feedsNode); if (!source.getSymbol().equals("")) //$NON-NLS-1$ { node = document.createElement("symbol"); //$NON-NLS-1$ node.appendChild(document.createTextNode(source.getSymbol())); feedsNode.appendChild(node); } if (source.getAccountId() != null) { node = document.createElement("account"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(source.getAccountId()))); feedsNode.appendChild(node); } node = document.createElement("quantity"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(source.getQuantity()))); feedsNode.appendChild(node); } if (security.getQuote() != null) { Quote quote = security.getQuote(); Node quoteNode = document.createElement("quote"); //$NON-NLS-1$ if (quote.getDate() != null) { node = document.createElement("date"); //$NON-NLS-1$ node.appendChild(document.createTextNode(dateTimeFormat.format(quote.getDate()))); quoteNode.appendChild(node); } node = document.createElement("last"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getLast()))); quoteNode.appendChild(node); node = document.createElement("bid"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getBid()))); quoteNode.appendChild(node); node = document.createElement("ask"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getAsk()))); quoteNode.appendChild(node); node = document.createElement("bidSize"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getBidSize()))); quoteNode.appendChild(node); node = document.createElement("askSize"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getAskSize()))); quoteNode.appendChild(node); node = document.createElement("volume"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(quote.getVolume()))); quoteNode.appendChild(node); element.appendChild(quoteNode); } Node dataNode = document.createElement("data"); //$NON-NLS-1$ element.appendChild(dataNode); if (security.getOpen() != null) { node = document.createElement("open"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getOpen()))); dataNode.appendChild(node); } if (security.getHigh() != null) { node = document.createElement("high"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getHigh()))); dataNode.appendChild(node); } if (security.getLow() != null) { node = document.createElement("low"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getLow()))); dataNode.appendChild(node); } if (security.getClose() != null) { node = document.createElement("close"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(security.getClose()))); dataNode.appendChild(node); } node = document.createElement("comment"); //$NON-NLS-1$ node.appendChild(document.createTextNode(security.getComment())); element.appendChild(node); for (Iterator iter = security.getSplits().iterator(); iter.hasNext();) { Split split = (Split) iter.next(); node = document.createElement("split"); //$NON-NLS-1$ node.setAttribute("date", dateTimeFormat.format(split.getDate())); //$NON-NLS-1$ node.setAttribute("fromQuantity", String.valueOf(split.getFromQuantity())); //$NON-NLS-1$ node.setAttribute("toQuantity", String.valueOf(split.getToQuantity())); //$NON-NLS-1$ element.appendChild(node); } for (Iterator iter = security.getDividends().iterator(); iter.hasNext();) { Dividend dividend = (Dividend) iter.next(); node = document.createElement("dividend"); //$NON-NLS-1$ node.setAttribute("date", dateTimeFormat.format(dividend.getDate())); //$NON-NLS-1$ node.setAttribute("value", String.valueOf(dividend.getValue())); //$NON-NLS-1$ element.appendChild(node); } }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public static void fixNode(Document dom, XPath xpath, String path, String nodeName, String value) { try {//from w w w .j av a2s . c om XPathExpression salRO = xpath.compile(path + "/" + nodeName); NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET); if (salRONodes.getLength() == 0) { XPathExpression salAddr = xpath.compile(path); NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET); if (salAddrNodes.getLength() > 0) { for (int t = 0; t < salAddrNodes.getLength(); t++) { Node AddrNode = salAddrNodes.item(t); Node city = dom.createElement(nodeName); Text cityValue = dom.createTextNode(value); city.appendChild(cityValue); AddrNode.appendChild(city); } } } } catch (Exception e) { _log.error("Error fixing node ..."); } }
From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java
public Document generateHibernateConfiguration(RDBMSDataSource rdbmsDataSource) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);// w ww . ja v a 2 s.co m factory.setExpandEntityReferences(false); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setEntityResolver(HibernateStorage.ENTITY_RESOLVER); Document document = documentBuilder .parse(DefaultStorageClassLoader.class.getResourceAsStream(HIBERNATE_CONFIG_TEMPLATE)); String connectionUrl = rdbmsDataSource.getConnectionURL(); String userName = rdbmsDataSource.getUserName(); String driverClass = rdbmsDataSource.getDriverClassName(); RDBMSDataSource.DataSourceDialect dialectType = rdbmsDataSource.getDialectName(); String dialect = getDialect(dialectType); String password = rdbmsDataSource.getPassword(); String indexBase = rdbmsDataSource.getIndexDirectory(); int connectionPoolMinSize = rdbmsDataSource.getConnectionPoolMinSize(); int connectionPoolMaxSize = rdbmsDataSource.getConnectionPoolMaxSize(); if (connectionPoolMaxSize == 0) { LOGGER.info("No value provided for property connectionPoolMaxSize of datasource " //$NON-NLS-1$ + rdbmsDataSource.getName() + ". Using default value: " //$NON-NLS-1$ + RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT); connectionPoolMaxSize = RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT; } setPropertyValue(document, "hibernate.connection.url", connectionUrl); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.username", userName); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.driver_class", driverClass); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dialect", dialect); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.password", password); //$NON-NLS-1$ // Sets up DBCP pool features setPropertyValue(document, "hibernate.dbcp.initialSize", String.valueOf(connectionPoolMinSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxActive", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxIdle", String.valueOf(10)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxTotal", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxWaitMillis", "60000"); //$NON-NLS-1$ //$NON-NLS-2$ Node sessionFactoryElement = document.getElementsByTagName("session-factory").item(0); //$NON-NLS-1$ if (rdbmsDataSource.supportFullText()) { /* <property name="hibernate.search.default.directory_provider" value="filesystem"/> <property name="hibernate.search.default.indexBase" value="/var/lucene/indexes"/> */ addProperty(document, sessionFactoryElement, "hibernate.search.default.directory_provider", //$NON-NLS-1$ "filesystem"); //$NON-NLS-1$ addProperty(document, sessionFactoryElement, "hibernate.search.default.indexBase", //$NON-NLS-1$ indexBase + '/' + storageName); addProperty(document, sessionFactoryElement, "hibernate.search.default.sourceBase", //$NON-NLS-1$ indexBase + '/' + storageName); addProperty(document, sessionFactoryElement, "hibernate.search.default.source", ""); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.search.default.exclusive_index_use", "false"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.search.lucene_version", "LUCENE_CURRENT"); //$NON-NLS-1$ //$NON-NLS-2$ } else { addProperty(document, sessionFactoryElement, "hibernate.search.autoregister_listeners", "false"); //$NON-NLS-1$ //$NON-NLS-2$ } if (dataSource.getCacheDirectory() != null && !dataSource.getCacheDirectory().isEmpty()) { /* <!-- Second level cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property> */ addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.cache.provider_class", //$NON-NLS-1$ "net.sf.ehcache.hibernate.EhCacheProvider"); //$NON-NLS-1$ addProperty(document, sessionFactoryElement, "hibernate.cache.use_query_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "net.sf.ehcache.configurationResourceName", "ehcache.xml"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Hibernate configuration does not define second level cache extensions due to datasource configuration."); //$NON-NLS-1$ } addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "false"); //$NON-NLS-1$ //$NON-NLS-2$ } // Override default configuration with values from configuration Map<String, String> advancedProperties = rdbmsDataSource.getAdvancedProperties(); for (Map.Entry<String, String> currentAdvancedProperty : advancedProperties.entrySet()) { setPropertyValue(document, currentAdvancedProperty.getKey(), currentAdvancedProperty.getValue()); } // Order of elements highly matters and mapping shall be declared after <property/> and before <event/>. Element mapping = document.createElement("mapping"); //$NON-NLS-1$ Attr resource = document.createAttribute("resource"); //$NON-NLS-1$ resource.setValue(HIBERNATE_MAPPING); mapping.getAttributes().setNamedItem(resource); sessionFactoryElement.appendChild(mapping); if (rdbmsDataSource.supportFullText()) { addEvent(document, sessionFactoryElement, "post-update", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ addEvent(document, sessionFactoryElement, "post-insert", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ addEvent(document, sessionFactoryElement, "post-delete", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ } else if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Hibernate configuration does not define full text extensions due to datasource configuration."); //$NON-NLS-1$ } return document; }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
/** * Performs replace processing according to section 11.1, para 5. *//*ww w .j a v a 2s .c o m*/ protected void submitReplaceText(Map response) throws XFormsException { if (getLogger().isDebugEnabled()) { getLogger().debug(this + " submit: replacing text"); } Node targetNode; if (this.targetExpr != null) { targetNode = XPathUtil .getAsNode( XPathCache.getInstance() .evaluate( this.instance == null ? evalInScopeContext() : this.model.getInstance(this.instance).getRootContext() .getNodeset(), 1, this.targetExpr, this.prefixMapping, this.xpathFunctionContext), 1); } else if (this.instance == null) { targetNode = this.model.getInstance(getInstanceId()).getInstanceDocument().getDocumentElement(); } else { targetNode = this.model.getInstance(this.instance).getInstanceDocument().getDocumentElement(); } final InputStream responseStream = (InputStream) response.get(XFormsProcessor.SUBMISSION_RESPONSE_STREAM); StringBuilder text = new StringBuilder(512); try { String contentType = (String) response.get("Content-Type"); String encoding = "UTF-8"; if (contentType != null) { final String[] contTypeEntries = contentType.split(", ?"); for (int i = 0; i < contTypeEntries.length; i++) { if (contTypeEntries[i].startsWith("charset=")) { encoding = contTypeEntries[i].substring(8); } } } byte[] buffer = new byte[512]; int bytesRead; while ((bytesRead = responseStream.read(buffer)) > 0) { text.append(new String(buffer, 0, bytesRead, encoding)); } responseStream.close(); } catch (Exception e) { // todo: check for response media type (needs submission response // refactoring) in order to dispatch xforms-link-exception throw new XFormsSubmitError("instance parsing failed", e, this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.PARSE_ERROR, getResourceURI(), 200d, null, "", "")); } if (targetNode == null) { throw new XFormsSubmitError("Invalid target", this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.TARGET_ERROR, getResourceURI(), 200d, null, "", "")); } else if (targetNode.getNodeType() == Node.ELEMENT_NODE) { while (targetNode.getFirstChild() != null) { targetNode.removeChild(targetNode.getFirstChild()); } targetNode.appendChild(targetNode.getOwnerDocument().createTextNode(text.toString())); } else if (targetNode.getNodeType() == Node.ATTRIBUTE_NODE) { targetNode.setNodeValue(text.toString()); } else { LOGGER.warn("Don't know how to handle targetNode '" + targetNode.getLocalName() + "', node is neither an element nor an attribute Node"); } // perform rebuild, recalculate, revalidate, and refresh this.model.rebuild(); this.model.recalculate(); this.model.revalidate(); this.container.refresh(); // deferred update behaviour UpdateHandler updateHandler = this.model.getUpdateHandler(); if (updateHandler != null) { updateHandler.doRebuild(false); updateHandler.doRecalculate(false); updateHandler.doRevalidate(false); updateHandler.doRefresh(false); } // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, constructEventInfo(response)); }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
/** * Create a tag of the form <templateId root="rootValue"> and append it under node * @param dom/* ww w .ja v a 2 s . c o m*/ * @param node * @param rootValue */ private void addTemplateId(Document dom, Node node, String rootValue) { Node dispTempl = dom.createElement("templateId"); Attr rootAttr = dom.createAttribute("root"); rootAttr.setValue(rootValue); dispTempl.getAttributes().setNamedItem(rootAttr); node.appendChild(dispTempl); }