List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
public void createPage(Connection con, Element elem, int type, MenuItemKey menuItemKey) throws VerticalCreateException { Element pageElem = XMLTool.getElement(elem, "page"); int pKey;//from w w w . java 2s . c o m Document pageDoc = XMLTool.createDocument(); pageDoc.appendChild(pageDoc.importNode(pageElem, true)); pKey = getPageHandler().createPage(XMLTool.documentToString(pageDoc)); PreparedStatement preparedStmt = null; try { preparedStmt = con.prepareStatement(MENU_ITEM_PAGE_UPDATE_KEY); preparedStmt.setInt(1, pKey); preparedStmt.setInt(2, type); preparedStmt.setInt(3, menuItemKey.toInt()); preparedStmt.executeUpdate(); } catch (SQLException e) { VerticalEngineLogger.errorCreate(this.getClass(), 10, "A database error occurred: %t", e); } finally { close(preparedStmt); } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
public void updatePage(Connection con, Element elem, int type, MenuItemKey key) throws VerticalUpdateException { Element pageElem = XMLTool.getElement(elem, "page"); int pKey = -1; Document pageDoc = XMLTool.createDocument(); pageDoc.appendChild(pageDoc.importNode(pageElem, true)); String tmp = pageElem.getAttribute("key"); if (tmp != null && tmp.length() > 0) { pKey = Integer.parseInt(tmp); try {/*from ww w . ja va 2 s .c om*/ getPageHandler().updatePage(XMLTool.documentToString(pageDoc)); } catch (VerticalUpdateException vue) { VerticalEngineLogger.errorUpdate(this.getClass(), 10, "A database error occurred: %t", vue); } } else { String MESSAGE_10 = "No page key found in XML."; VerticalEngineLogger.errorUpdate(this.getClass(), 20, MESSAGE_10, null); } PreparedStatement preparedStmt = null; try { preparedStmt = con.prepareStatement(MENU_ITEM_PAGE_UPDATE_KEY); preparedStmt.setInt(1, pKey); preparedStmt.setInt(2, type); preparedStmt.setInt(3, key.toInt()); preparedStmt.executeUpdate(); } catch (SQLException e) { VerticalEngineLogger.errorUpdate(this.getClass(), 30, "A database error occurred: %t", e); } finally { close(preparedStmt); } }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * // w ww. ja v a 2s.c o m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExact(String model, String name, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExact: " + model + " name: " + name + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dc:title", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); } if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dcterms:alternative", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); client = new HttpClient(); method = new GetMethod(queryUrl); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); } if (method.getStatusCode() == 200) { results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again if (logger.isDebugEnabled()) { logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); } if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder .parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; //throw new RuntimeException(e); } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private void copyMenu(CopyContext copyContext, Element menuElem) throws VerticalCopyException, VerticalCreateException, VerticalUpdateException, VerticalSecurityException { if (menuElem != null) { User user = copyContext.getUser(); int oldMenuKey = Integer.parseInt(menuElem.getAttribute("key")); //if (copyContext.getOldSiteKey() != copyContext.getNewSiteKey()) // menuElem.setAttribute("sitekey", String.valueOf(copyContext.getNewSiteKey())); //else {// ww w . j a v a2 s. c om Element nameElem = XMLTool.getElement(menuElem, "name"); Text text = (Text) nameElem.getFirstChild(); Map translationMap = languageMap.getTranslationMap(user.getSelectedLanguageCode()); text.setData(text.getData() + " (" + translationMap.get("%txtCopy%") + ")"); //} Element elem = XMLTool.getElement(menuElem, "firstpage"); String oldFirstPageKey = elem.getAttribute("key"); elem.removeAttribute("key"); elem = XMLTool.getElement(menuElem, "loginpage"); String oldLoginPageKey = elem.getAttribute("key"); elem.removeAttribute("key"); elem = XMLTool.getElement(menuElem, "errorpage"); String oldErrorPageKey = elem.getAttribute("key"); elem.removeAttribute("key"); String oldDefaultPageTemplateKey = null; elem = XMLTool.getElement(menuElem, "defaultpagetemplate"); if (elem != null) { oldDefaultPageTemplateKey = elem.getAttribute("pagetemplatekey"); elem.removeAttribute("pagetemplatekey"); } Document newDoc = XMLTool.createDocument(); Element newMenuElem = (Element) newDoc.importNode(menuElem, true); newDoc.appendChild(newMenuElem); Element menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems"); newMenuElem.removeChild(menuitemsElem); SiteKey menuKey = createMenu(user, copyContext, newDoc, false); // copy content objects and page templates ContentObjectHandler contentObjectHandler = getContentObjectHandler(); contentObjectHandler.copyContentObjects(oldMenuKey, copyContext); PageTemplateHandler pageTemplateHandler = getPageTemplateHandler(); pageTemplateHandler.copyPageTemplates(oldMenuKey, copyContext); Document doc = getMenu(user, menuKey.toInt(), true, true); Element docElem = doc.getDocumentElement(); newMenuElem = (Element) docElem.getFirstChild(); doc.replaceChild(newMenuElem, docElem); Element newMenuitemsElem = (Element) doc.importNode(menuitemsElem, true); menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems"); newMenuElem.replaceChild(newMenuitemsElem, menuitemsElem); // prepare copy of menu items prepareCopy(newMenuitemsElem, copyContext); updateMenu(user, copyContext, doc, false); if (oldFirstPageKey != null && oldFirstPageKey.length() > 0) { elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "firstpage"); elem.setAttribute("key", String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldFirstPageKey)))); } if (oldLoginPageKey != null && oldLoginPageKey.length() > 0) { elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "loginpage"); elem.setAttribute("key", String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldLoginPageKey)))); } if (oldErrorPageKey != null && oldErrorPageKey.length() > 0) { elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "errorpage"); elem.setAttribute("key", String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldErrorPageKey)))); } if (oldDefaultPageTemplateKey != null && oldDefaultPageTemplateKey.length() > 0) { elem = XMLTool.createElement(doc, newMenuElem, "defaultpagetemplate"); elem.setAttribute("pagetemplatekey", String .valueOf(copyContext.getPageTemplateKey(Integer.parseInt(oldDefaultPageTemplateKey)))); } if (copyContext.isIncludeContents()) { menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems"); prepareUpdate(menuitemsElem); } // update default css Element menudataElem = XMLTool.getElement(newMenuElem, "menudata"); Element defaultcssElem = XMLTool.getElement(menudataElem, "defaultcss"); if (defaultcssElem != null) { String cssKey = defaultcssElem.getAttribute("key"); if (cssKey != null && cssKey.length() > 0) { defaultcssElem.setAttribute("key", cssKey); } } updateMenu(user, copyContext, doc, true); // post-process content objects and page templates contentObjectHandler.copyContentObjectsPostOp(oldMenuKey, copyContext); pageTemplateHandler.copyPageTemplatesPostOp(oldMenuKey, copyContext); } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private void updateMenuItemData(User user, Element menuItemElem, int type, MenuItemKey parent, int order) throws VerticalUpdateException { String tmp;//from w w w . ja va 2 s .com boolean modified = "modified".equals(menuItemElem.getAttribute("modified")); Connection con = null; PreparedStatement preparedStmt = null; try { con = getConnection(); // update the main table: int psCounter = 1; if (modified) { preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE); } else { preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE_NO_DATA); } //} // name Element tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENUITEM_NAME); String name = XMLTool.getElementText(tmp_elem); validateMenuItemName(name); StringReader sreader = new StringReader(name); preparedStmt.setCharacterStream(psCounter++, sreader, name.length()); if (parent != null) { preparedStmt.setInt(psCounter++, parent.toInt()); } else { preparedStmt.setNull(psCounter++, Types.INTEGER); } // order preparedStmt.setInt(psCounter++, order); Element dataElem; if (modified) { dataElem = XMLTool.getElement(menuItemElem, "data"); // parameters tmp_elem = XMLTool.getElement(menuItemElem, "parameters"); if (tmp_elem != null) { dataElem.appendChild(tmp_elem); } } else { dataElem = null; } // alternative name: tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENU_NAME); if (tmp_elem != null) { tmp = XMLTool.getElementText(tmp_elem); preparedStmt.setString(psCounter++, tmp); } else { preparedStmt.setNull(psCounter++, Types.VARCHAR); } // visibility: tmp = menuItemElem.getAttribute("visible"); if ("no".equals(tmp)) { preparedStmt.setInt(psCounter++, 1); } else { preparedStmt.setInt(psCounter++, 0); } // description: tmp_elem = XMLTool.getElement(menuItemElem, "description"); String data = XMLTool.getElementText(tmp_elem); if (data == null) { data = ""; } StringReader reader = new StringReader(data); preparedStmt.setCharacterStream(psCounter++, reader, data.length()); // keywords tmp_elem = XMLTool.getElement(menuItemElem, "keywords"); String keywords = XMLTool.getElementText(tmp_elem); if (keywords == null || keywords.length() == 0) { preparedStmt.setNull(psCounter++, Types.VARCHAR); } else { StringReader keywordReader = new StringReader(keywords); preparedStmt.setCharacterStream(psCounter++, keywordReader, keywords.length()); } // language String lanKey = menuItemElem.getAttribute("languagekey"); if ((lanKey != null) && (lanKey.length() > 0)) { preparedStmt.setInt(psCounter++, Integer.parseInt(lanKey)); } else { preparedStmt.setNull(psCounter++, Types.INTEGER); } // get menuitem key: tmp = menuItemElem.getAttribute("key"); int key = Integer.parseInt(tmp); // owner String ownerKey = menuItemElem.getAttribute("owner"); // modifier String modifierKey = menuItemElem.getAttribute("modifier"); if (modified && type == 4) { //byte[] document = null; Element docElem = XMLTool.getElement(menuItemElem, "document"); dataElem.appendChild(docElem); } preparedStmt.setString(psCounter++, ownerKey); preparedStmt.setString(psCounter++, modifierKey); RunAsType runAs = RunAsType.INHERIT; String runAsStr = menuItemElem.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(psCounter++, runAs.getKey()); // displayname: tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_DISPLAY_NAME); if (tmp_elem == null) { throw new IllegalArgumentException("Displayname must be set"); } else { tmp = XMLTool.getElementText(tmp_elem); preparedStmt.setString(psCounter++, tmp); } // data if (modified) { Document dataDoc = XMLTool.createDocument(); dataDoc.appendChild(dataDoc.importNode(dataElem, true)); byte[] bytes = XMLTool.documentToBytes(dataDoc, "UTF-8"); preparedStmt.setBinaryStream(psCounter++, new ByteArrayInputStream(bytes), bytes.length); } preparedStmt.setInt(psCounter, key); preparedStmt.executeUpdate(); if (multicaster.hasListeners()) { int menuKey = getMenuKeyByMenuItem(key); MenuHandlerEvent e = new MenuHandlerEvent(user, menuKey, key, name, this); multicaster.updatedMenuItem(e); } } catch (SQLException sqle) { VerticalEngineLogger.errorUpdate(this.getClass(), 20, "SQL error while updating menuitem data.", sqle); } finally { close(preparedStmt); close(con); } }
From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java
public void handlerCustom(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems, String operation) throws VerticalAdminException, VerticalEngineException { int menuKey = formItems.getInt("menukey", -1); if (operation.equals("datasourcepreview")) { if (formItems.containsKey("datasources")) { int key = formItems.getInt("key", -1); User user = securityService.getLoggedInAdminConsoleUser(); User runAsUser = null;// w w w .j a v a 2s .c om if (key != -1) { runAsUser = admin.getContentObjectRunAs(key); } if (runAsUser != null) { user = runAsUser; } Document doc; Document documentAsW3cDocument = XMLTool.createDocument("document"); Element rootElem = documentAsW3cDocument.getDocumentElement(); if (verticalProperties.isStoreXHTMLOn()) { XMLTool.createXHTMLNodes(documentAsW3cDocument, rootElem, formItems.getString("document", ""), true); } else { XMLTool.createCDATASection(documentAsW3cDocument, rootElem, formItems.getString("document", "")); } final SiteKey siteKey = new SiteKey(menuKey); String xmlData; XMLDocument dataSourcesXml = XMLDocumentFactory.create(formItems.getString("datasources")); String docType = formItems.getString("documenttype"); boolean pageTemplateDataource = "pagetemplate".equals(docType); try { if (pageTemplateDataource) { xmlData = doGetPageTemplateDatasourceResult(user, siteKey, dataSourcesXml); } else { XMLDocument portletDocumentAsXmlDocument = XMLDocumentFactory.create(documentAsW3cDocument); xmlData = doGetPortletDatasourceResult(user, siteKey, dataSourcesXml, portletDocumentAsXmlDocument); } } catch (final Exception e) { final String resultRootName = verticalProperties.getDatasourceDefaultResultRootElement(); final XMLDocument failedDatasourceDoc = XMLDocumentFactory .create(DataSourceFailedXmlCreator.buildExceptionDocument(resultRootName, e)); xmlData = failedDatasourceDoc.getAsString(); } if (xmlData != null) { doc = XMLTool.domparse(xmlData); } else { doc = XMLTool.createDocument("datasources"); } spoolDocument(response, doc); } } else if (operation.equals("updatestylesheet")) { User user = securityService.getLoggedInAdminConsoleUser(); String key = formItems.getString("key", null); boolean createContentObject = (key == null || key.length() == 0); Document coDoc = buildContentObjectXML(admin, formItems, createContentObject, true); NodeList coNodes = coDoc.getElementsByTagName("contentobject"); Element contentobject = (Element) coNodes.item(0); ResourceKey borderStyleSheetKey = ResourceKey.parse(formItems.getString("borderstylesheet", null)); if (borderStyleSheetKey != null) { addStyleSheet(contentobject, "borderstylesheet_xsl", borderStyleSheetKey); } ResourceKey objectStyleSheetKey = ResourceKey.parse(formItems.getString("stylesheet", null)); if (objectStyleSheetKey != null) { addStyleSheet(contentobject, "objectstylesheet_xsl", objectStyleSheetKey); } String queryParam = ""; NodeList nodeList = contentobject.getElementsByTagName("datasources"); if (nodeList.getLength() > 0) { Document doc = XMLTool.createDocument(); doc.appendChild(doc.importNode(nodeList.item(0), true)); queryParam = XMLTool.documentToString(doc); queryParam = StringUtil.formatXML(queryParam, 2); } if (key != null) { int cobKey = Integer.parseInt(key); // Add pages that uses this content object String menuItemsXML; menuItemsXML = admin.getMenuItemsByContentObject(user, cobKey); Document menuItemsDoc = XMLTool.domparse(menuItemsXML); contentobject.appendChild(coDoc.importNode(menuItemsDoc.getDocumentElement(), true)); // Add frameworks that uses this content object String pageTemplatesXML = admin.getPageTemplatesByContentObject(cobKey); Document pageTemplatesDoc = XMLTool.domparse(pageTemplatesXML); contentobject.appendChild(coDoc.importNode(pageTemplatesDoc.getDocumentElement(), true)); } ExtendedMap parameters = new ExtendedMap(); addCommonParameters(admin, user, request, parameters, -1, menuKey); if (createContentObject) { parameters.put("create", "1"); } else { parameters.put("create", "0"); } if (queryParam != null && queryParam.length() > 0) { parameters.put("queryparam", queryParam); } else { parameters.put("queryparam", "<?xml version=\"1.0\" ?><datasources/>"); } parameters.put("page", String.valueOf(request.getParameter("page"))); parameters.put("referer", formItems.get("referer")); parameters.put("subop", formItems.getString("subop", "")); parameters.put("menukey", formItems.getString("menukey")); parameters.put("rememberselectedtab", formItems.getString("rememberselectedtab", "")); parameters.put("script", formItems.getString("script", "")); parameters.put("fieldname", formItems.getString("fieldname", null)); parameters.put("fieldrow", formItems.getString("fieldrow", null)); UserEntity defaultRunAsUser = siteDao.findByKey(menuKey).resolveDefaultRunAsUser(); String defaultRunAsUserName = "NA"; if (defaultRunAsUser != null) { defaultRunAsUserName = defaultRunAsUser.getDisplayName(); } parameters.put("defaultRunAsUser", defaultRunAsUserName); transformXML(request, response, coDoc, "contentobject_form.xsl", parameters); } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private int createMenuItem(User user, CopyContext copyContext, Element menuItemElement, SiteKey siteKey, int order, MenuItemKey parentKey, boolean useOldKey) throws VerticalCreateException, VerticalSecurityException { // security check: if (!getSecurityHandler().validateMenuItemCreate(user, siteKey.toInt(), parentKey == null ? -1 : parentKey.toInt())) { VerticalEngineLogger.errorSecurity(this.getClass(), 10, "Not allowed to create menuitem in this position.", null); }// w w w. java 2 s. c o m String menuItemName = XMLTool .getElementText(XMLTool.getElement(menuItemElement, ELEMENT_NAME_MENUITEM_NAME)); if (StringUtils.isEmpty(menuItemName)) { menuItemName = generateMenuItemName(menuItemElement); } menuItemName = ensureUniqueMenuItemName(siteKey, parentKey, menuItemName, null); // check whether name is unique for this parent if (menuItemNameExists(siteKey, parentKey, menuItemName, null)) { VerticalEngineLogger.errorCreate(this.getClass(), 20, "Menu item name already exists on this level: %0", new Object[] { menuItemName }, null); } Element tmp_element; Hashtable<String, Integer> menuItemTypes = getMenuItemTypesAsHashtable(); // Get menuitem type: String miType = menuItemElement.getAttribute("type"); Integer type = menuItemTypes.get(miType); if (type == null) { VerticalEngineLogger.errorCreate(this.getClass(), 20, "Invalid menu item type %0.", new Object[] { type }, null); } Connection con = null; PreparedStatement preparedStmt = null; MenuItemKey menuItemKey = null; try { con = getConnection(); // key String keyStr = menuItemElement.getAttribute("key"); if (!useOldKey || keyStr == null || keyStr.length() == 0) { try { menuItemKey = new MenuItemKey(getNextKey(MENU_ITEM_TABLE)); } catch (VerticalKeyException e) { VerticalEngineLogger.errorCreate(this.getClass(), 30, "Error generating key for tMenuItem.", e); } } else { menuItemKey = new MenuItemKey(keyStr); } if (copyContext != null) { copyContext.putMenuItemKey(Integer.parseInt(keyStr), menuItemKey.toInt()); } String tmp; preparedStmt = con.prepareStatement(MENU_ITEM_INSERT); preparedStmt.setInt(1, menuItemKey.toInt()); // element: name validateMenuItemName(menuItemName); preparedStmt.setString(2, menuItemName); // menu key: preparedStmt.setInt(3, siteKey.toInt()); // attribute: menu item type preparedStmt.setInt(4, type); // parent if (parentKey == null) { preparedStmt.setNull(5, Types.INTEGER); } else { preparedStmt.setInt(5, parentKey.toInt()); } // order: preparedStmt.setInt(6, order); // pre-fetch data element Element dataElem = XMLTool.getElement(menuItemElement, "data"); // element: parameters tmp_element = XMLTool.getElement(menuItemElement, "parameters"); if (tmp_element != null) { dataElem.appendChild(tmp_element); } // alternative name: tmp_element = XMLTool.getElement(menuItemElement, ELEMENT_NAME_MENU_NAME); if (tmp_element != null) { tmp = XMLTool.getElementText(tmp_element); preparedStmt.setString(7, tmp); } else { preparedStmt.setNull(7, Types.VARCHAR); } // visibility: tmp = menuItemElement.getAttribute("visible"); if ("no".equals(tmp)) { preparedStmt.setInt(8, 1); } else { preparedStmt.setInt(8, 0); } // description: tmp_element = XMLTool.getElement(menuItemElement, "description"); String data = XMLTool.getElementText(tmp_element); if (data != null) { StringReader reader = new StringReader(data); preparedStmt.setCharacterStream(9, reader, data.length()); } else { preparedStmt.setNull(9, Types.VARCHAR); } if (type == 4) { Element docElem = XMLTool.getElement(menuItemElement, "document"); if (docElem != null) { dataElem.appendChild(docElem); } } // attribute: owner/modifier String ownerKey = menuItemElement.getAttribute("owner"); preparedStmt.setString(10, ownerKey); preparedStmt.setString(11, ownerKey); // data if (dataElem != null) { Document dataDoc = XMLTool.createDocument(); dataDoc.appendChild(dataDoc.importNode(dataElem, true)); byte[] bytes = XMLTool.documentToBytes(dataDoc, "UTF-8"); preparedStmt.setBinaryStream(12, new ByteArrayInputStream(bytes), bytes.length); } else { preparedStmt.setNull(12, Types.BLOB); } // keywords tmp_element = XMLTool.getElement(menuItemElement, "keywords"); String keywords = XMLTool.getElementText(tmp_element); if (keywords == null || keywords.length() == 0) { preparedStmt.setNull(13, Types.VARCHAR); } else { StringReader keywordReader = new StringReader(keywords); preparedStmt.setCharacterStream(13, keywordReader, keywords.length()); } // language String lanKey = menuItemElement.getAttribute("languagekey"); if ((lanKey != null) && (lanKey.length() > 0)) { preparedStmt.setInt(14, Integer.parseInt(lanKey)); } else { preparedStmt.setNull(14, Types.INTEGER); } RunAsType runAs = RunAsType.INHERIT; String runAsStr = menuItemElement.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(15, runAs.getKey()); // Display-name String displayName = getElementValue(menuItemElement, ELEMENT_NAME_DISPLAY_NAME); preparedStmt.setString(16, displayName); // execute statement: preparedStmt.executeUpdate(); // Create type specific data. switch (type) { case 1: // page createPage(con, menuItemElement, type, menuItemKey); break; case 2: // URL createOrUpdateURL(con, menuItemElement, menuItemKey); break; case 4: // document: nothing // page Element pageElem = XMLTool.getElement(menuItemElement, "page"); PageTemplateKey pageTemplateKey = new PageTemplateKey(pageElem.getAttribute("pagetemplatekey")); PageTemplateType pageTemplateType = getPageTemplateHandler().getPageTemplateType(pageTemplateKey); if (pageTemplateType == PageTemplateType.SECTIONPAGE || pageTemplateType == PageTemplateType.NEWSLETTER) { createSection(menuItemElement, menuItemKey); } createPage(con, menuItemElement, type, menuItemKey); break; case 5: // label break; case 6: // section createSection(menuItemElement, menuItemKey); break; case 7: // shortcut createOrOverrideShortcut(menuItemElement, menuItemKey); break; default: VerticalEngineLogger.errorCreate(this.getClass(), 70, "Unknown menuitem type: %0", new Object[] { type }, null); } // set contentkey if present String contentKeyStr = menuItemElement.getAttribute("contentkey"); if (contentKeyStr.length() == 0) { contentKeyStr = "-1"; } setMenuItemContentKey(menuItemKey, Integer.parseInt(contentKeyStr)); // fire event if (multicaster.hasListeners() && copyContext == null) { MenuHandlerEvent e = new MenuHandlerEvent(user, siteKey.toInt(), menuItemKey.toInt(), menuItemName, this); multicaster.createdMenuItem(e); } UserSpecification userSpecification = new UserSpecification(); userSpecification.setDeletedState(UserSpecification.DeletedState.ANY); userSpecification.setKey(new UserKey(ownerKey)); UserEntity owner = userDao.findSingleBySpecification(userSpecification); String ownerGroupKey = null; if (owner.getUserGroup() != null) { ownerGroupKey = owner.getUserGroup().getGroupKey().toString(); } getSecurityHandler().inheritMenuItemAccessRights(siteKey.toInt(), parentKey == null ? -1 : parentKey.toInt(), menuItemKey.toInt(), ownerGroupKey); // Create other Element menuItemsElement = XMLTool.getElement(menuItemElement, "menuitems"); if (menuItemsElement != null) { Element[] elems = XMLTool.getElements(menuItemsElement); for (int i = 0; i < elems.length; i++) { createMenuItem(user, copyContext, elems[i], siteKey, i, menuItemKey, useOldKey); } } } catch (SQLException e) { VerticalEngineLogger.errorCreate(this.getClass(), 40, "A database error occurred: %t", e); } finally { close(preparedStmt); close(con); } return menuItemKey.toInt(); }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
public Document getMenuItemsByContentObject(User user, int cobKey) { Connection con = null;/*from ww w . j ava 2 s .co m*/ PreparedStatement preparedStmt = null; ResultSet resultSet = null; Document doc = XMLTool.createDocument("menuitems"); try { con = getConnection(); preparedStmt = con.prepareStatement(MENU_ITEMS_BY_CONTENTOBJECT); preparedStmt.setInt(1, cobKey); resultSet = preparedStmt.executeQuery(); Element rootElem = doc.getDocumentElement(); while (resultSet.next()) { int meiKey = resultSet.getInt("mei_lKey"); Document menuItemDoc = getMenuItem(user, meiKey, -1, false, false, false, false, true, false, false, 1); Element tmpElem = (Element) menuItemDoc.getDocumentElement().getFirstChild(); if (tmpElem != null) { // Fix for nullpointerexception discovered on BergHansen, user did not have access to menuitem rootElem.appendChild(doc.importNode(tmpElem, true)); } } } catch (SQLException e) { VerticalEngineLogger.warn(this.getClass(), 10, "A database error occurred. XML may be incomplete.", e); } finally { close(resultSet); close(preparedStmt); close(con); } return doc; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * replace elements in originalDom with modifiedDom according to listed * xPaths, if the originalDom has elements not listed in the xPath, it will * be kept untouched. in the HashMap<String, String> xPathPairs, the key is * the path in the source xml, and the value is the xpath for the final * note*: the if the xpath has attributes, it's not going to work... need to * do a custom implementation when that use case happened... * //from w w w. java2 s . c o m * @param originalDom * @param modifiedDom * @param xPaths * @return * @throws XPathExpressionException */ private Document replaceByXPaths(final Document originalDom, final Document modifiedDom, Map<String, String> xPathPairs) throws XPathExpressionException { Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element lastChild = null; for (Entry<String, String> xPathPair : xPathPairs.entrySet()) { /** * basically, this is to copy the element specified in srcXPath, and * replace/add it to the position pointed by destXPath... */ String srcXPath = xPathPair.getKey(); logger.debug("srcXPath: " + srcXPath); String destXPath = xPathPair.getValue(); logger.debug("destXPath: " + destXPath); XPath xPath = getXPathInstance(); // find all the nodes specified by destXPath in the originalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); // remove this node from its parent... c.getParentNode().removeChild(c); } // create the node structure first. and return the last child of the // path... the right most node... lastChild = createElementStructureByPath(finalDomRoot, destXPath); List<String> nodeNameList = getNodeList(destXPath); String lastNodeName = nodeNameList.get(nodeNameList.size() - 1); xPath.reset(); // find all the nodes specified by srcXPath in the modifiedDom NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET)); int l = nodeList.getLength(); logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath); Node currentNode = null; for (int i = 0; i < l; i++) { currentNode = nodeList.item(i); // the name of the last node in srcXPath might not be the same // as the name of the last node in destXPath Element lastElement = finalDom.createElement(lastNodeName); // NodeList currentNodeChildNodes = currentNode.getChildNodes(); // int s = currentNodeChildNodes.getLength(); // for(int j = 0; j < s; j++){ // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j), // true)); // } if (currentNode.hasAttributes()) { NamedNodeMap attributes = currentNode.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { String attribute_name = attributes.item(j).getNodeName(); String attribute_value = attributes.item(j).getNodeValue(); lastElement.setAttribute(attribute_name, attribute_value); } } while (currentNode.hasChildNodes()) { Node kid = currentNode.getFirstChild(); currentNode.removeChild(kid); lastElement.appendChild(finalDom.importNode(kid, true)); } lastChild.appendChild(lastElement); } } return finalDom; }
From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java
/** * This method takes the SOAP request that come from the WSP and removes * the elements that need to be removed per the SAML Profiles spec. * //w ww . j a va 2 s.c o m * @param samlSession * @param authnState * @return true, if successful */ private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) { this.logger.debug("Step 3 of 5: Process SOAP Request"); try { String expression = "/S:Envelope/S:Header/paos:Request"; Document dom = authnState.getSoapRequestDom(); Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); if (node != null) { // Save the response consumer URL to samlSession String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL") .getTextContent(); logger.debug("Loaded response consumer URL {}", responseConsumerURL); authnState.setResponseConsumerURL(responseConsumerURL); // Save the PAOS MessageID, if present Node paosMessageID = node.getAttributes().getNamedItem("messageID"); if (paosMessageID != null) authnState.setPaosMessageID(paosMessageID.getTextContent()); else authnState.setPaosMessageID(null); // This removes the paos:Request node node.getParentNode().removeChild(node); // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response expression = "/S:Envelope/S:Header/ecp:RelayState"; node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); if (node != null) { Element relayStateElement = (Element) node; authnState.setRelayStateElement(relayStateElement); node.getParentNode().removeChild(node); } // On to the ecp:Request for removal expression = "/S:Envelope/S:Header/ecp:Request"; node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); node.getParentNode().removeChild(node); // Now add some namespace bindings to the SOAP Header expression = "/S:Envelope/S:Header"; Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); // Add new elements to S:Header Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework"); newElement.setAttribute("version", "2.0"); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender"); newElement.setAttribute("providerID", samlSession.getPortalEntityID()); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID"); String messageID = generateMessageID(); newElement.setTextContent(messageID); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action"); newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest"); soapHeader.appendChild(newElement); // This is the wsse:Security element Element securityElement = dom.createElementNS( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:Security"); securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1"); Element createdElement = dom.createElement("wsu:Created"); // The examples use Zulu time zone, not local TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); sdf.setTimeZone(zuluTimeZone); createdElement.setTextContent(sdf.format(new Date())); newElement = dom.createElementNS( "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "wsu:Timestamp"); newElement.appendChild(createdElement); securityElement.appendChild(newElement); // Finally, insert the original SAML assertion Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(), true); securityElement.appendChild(samlAssertionNode); soapHeader.appendChild(securityElement); // Store the modified SOAP Request in the SAML Session String modifiedSOAPRequest = writeDomToString(dom); authnState.setModifiedSOAPRequest(modifiedSOAPRequest); logger.debug("Completed processing of SOAP request"); return true; } logger.debug("Failed to process SOAP request using expression {}", expression); } catch (XPathExpressionException ex) { logger.error("Programming error. Invalid XPath expression.", ex); throw new DelegatedAuthenticationRuntimeException("Programming error. Invalid XPath expression.", ex); } return false; }