List of usage examples for org.dom4j Node TEXT_NODE
short TEXT_NODE
To view the source code for org.dom4j Node TEXT_NODE.
Click Source Link
From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java
License:Open Source License
/** * Extract value from a single node/*from ww w . j a v a2 s.c om*/ * <br> * <UL> * <LI>If an Element return the element reference. * <LI>If an Attribute return the attribute value * <LI>If text (or CDATA) return it. * <LI>If null return null. * @param node Node from which to extract a value * @return Reference to Element, or String representation of value. */ private Object getSingleValuedResult(Node node) { Object result = null; switch (node.getNodeType()) { case Node.ELEMENT_NODE: result = (Element) node; break; case Node.ATTRIBUTE_NODE: result = ((Attribute) node).getValue(); break; case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: //Not sure about this one! result = node.getText(); break; } return result; }
From source file:org.opencms.webdav.CmsWebdavServlet.java
License:Open Source License
/** * Process a LOCK WebDAV request for the specified resource.<p> * //from w w w. ja v a 2 s . c o m * @param req the servlet request we are processing * @param resp the servlet response we are creating * * @throws IOException if an input/output error occurs */ @SuppressWarnings("unchecked") protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); // Check if webdav is set to read only if (m_readOnly) { resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0)); } return; } // Check if resource is locked if (isLocked(req)) { resp.setStatus(CmsWebdavStatus.SC_LOCKED); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path)); } return; } CmsRepositoryLockInfo lock = new CmsRepositoryLockInfo(); // Parsing depth header String depthStr = req.getHeader(HEADER_DEPTH); if (depthStr == null) { lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE); } else { if (depthStr.equals("0")) { lock.setDepth(0); } else { lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE); } } // Parsing timeout header int lockDuration = CmsRepositoryLockInfo.TIMEOUT_INFINITE_VALUE; lock.setExpiresAt(System.currentTimeMillis() + (lockDuration * 1000)); int lockRequestType = LOCK_CREATION; Element lockInfoNode = null; try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getRootElement(); lockInfoNode = rootElement; } catch (Exception e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information Iterator<Element> iter = lockInfoNode.elementIterator(); Element lockScopeNode = null; Element lockTypeNode = null; Element lockOwnerNode = null; while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentElem.getName(); if (nodeName.endsWith(TAG_LOCKSCOPE)) { lockScopeNode = currentElem; } if (nodeName.endsWith(TAG_LOCKTYPE)) { lockTypeNode = currentElem; } if (nodeName.endsWith(TAG_OWNER)) { lockOwnerNode = currentElem; } break; default: break; } } if (lockScopeNode != null) { iter = lockScopeNode.elementIterator(); while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentElem.getName(); if (tempScope.indexOf(':') != -1) { lock.setScope(tempScope.substring(tempScope.indexOf(':') + 1)); } else { lock.setScope(tempScope); } break; default: break; } } if (lock.getScope() == null) { // Bad request resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { iter = lockTypeNode.elementIterator(); while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentElem.getName(); if (tempType.indexOf(':') != -1) { lock.setType(tempType.substring(tempType.indexOf(':') + 1)); } else { lock.setType(tempType); } break; default: break; } } if (lock.getType() == null) { // Bad request resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { iter = lockOwnerNode.elementIterator(); while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: lock.setOwner(lock.getOwner() + currentElem.getStringValue()); break; case Node.ELEMENT_NODE: lock.setOwner(lock.getOwner() + currentElem.getStringValue()); break; default: break; } } if (lock.getOwner() == null) { // Bad request resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST); } } else { lock.setOwner(""); } } lock.setPath(path); lock.setUsername(m_username); if (lockRequestType == LOCK_REFRESH) { CmsRepositoryLockInfo currentLock = m_session.getLock(path); if (currentLock == null) { lockRequestType = LOCK_CREATION; } } if (lockRequestType == LOCK_CREATION) { try { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_1, lock.getOwner())); } boolean result = m_session.lock(path, lock); if (result) { // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader(HEADER_LOCKTOKEN, "<opaquelocktoken:" + generateLockToken(req, lock) + ">"); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_FAILED_0)); } } else { resp.setStatus(CmsWebdavStatus.SC_LOCKED); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_SUCCESS_0)); } return; } } catch (CmsVfsResourceNotFoundException rnfex) { resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path)); } return; } catch (CmsSecurityException sex) { resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_PERMISSION_0)); } return; } catch (CmsException ex) { resp.setStatus(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR); if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "LOCK", path), ex); } return; } } // Set the status, then generate the XML response containing // the lock information Document doc = DocumentHelper.createDocument(); Element propElem = doc.addElement(new QName(TAG_PROP, Namespace.get(DEFAULT_NAMESPACE))); Element lockElem = addElement(propElem, TAG_LOCKDISCOVERY); addLockElement(lock, lockElem, generateLockToken(req, lock)); resp.setStatus(CmsWebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); doc.write(writer); writer.close(); }
From source file:org.opencms.webdav.CmsWebdavServlet.java
License:Open Source License
/** * Process a PROPFIND WebDAV request for the specified resource.<p> * //from w w w.j a va 2 s .c o m * @param req the servlet request we are processing * @param resp the servlet response we are creating * * @throws IOException if an input/output error occurs */ protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); if (!m_listings) { // Get allowed methods StringBuffer methodsAllowed = determineMethodsAllowed(getRelativePath(req)); resp.addHeader(HEADER_ALLOW, methodsAllowed.toString()); resp.setStatus(CmsWebdavStatus.SC_METHOD_NOT_ALLOWED); return; } // Properties which are to be displayed. List<String> properties = new Vector<String>(); // Propfind depth int depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader(HEADER_DEPTH); if (depthStr == null) { depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equalsIgnoreCase(DEPTH_INFINITY)) { depth = CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE; } } Element propNode = null; try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(req.getInputStream()); // Get the root element of the document Element rootElement = document.getRootElement(); @SuppressWarnings("unchecked") Iterator<Element> iter = rootElement.elementIterator(); while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentElem.getName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentElem; } if (currentElem.getName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentElem.getName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; default: break; } } } catch (Exception e) { // Most likely there was no content : we use the defaults. } if (propNode != null) { if (type == FIND_BY_PROPERTY) { @SuppressWarnings("unchecked") Iterator<Element> iter = propNode.elementIterator(); while (iter.hasNext()) { Element currentElem = iter.next(); switch (currentElem.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentElem.getName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring(nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.add(propertyName); break; default: break; } } } } boolean exists = m_session.exists(path); if (!exists) { resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path)); } return; } I_CmsRepositoryItem item = null; try { item = m_session.getItem(path); } catch (CmsException e) { resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND); return; } resp.setStatus(CmsWebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object Document doc = DocumentHelper.createDocument(); Element multiStatusElem = doc.addElement(new QName(TAG_MULTISTATUS, Namespace.get("D", DEFAULT_NAMESPACE))); if (depth == 0) { parseProperties(req, multiStatusElem, item, type, properties); } else { // The stack always contains the object of the current level Stack<I_CmsRepositoryItem> stack = new Stack<I_CmsRepositoryItem>(); stack.push(item); // Stack of the objects one level below Stack<I_CmsRepositoryItem> stackBelow = new Stack<I_CmsRepositoryItem>(); while ((!stack.isEmpty()) && (depth >= 0)) { I_CmsRepositoryItem currentItem = stack.pop(); parseProperties(req, multiStatusElem, currentItem, type, properties); if ((currentItem.isCollection()) && (depth > 0)) { try { List<I_CmsRepositoryItem> list = m_session.list(currentItem.getName()); Iterator<I_CmsRepositoryItem> iter = list.iterator(); while (iter.hasNext()) { I_CmsRepositoryItem element = iter.next(); stackBelow.push(element); } } catch (CmsException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_LIST_ITEMS_ERROR_1, currentItem.getName()), e); } return; } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<I_CmsRepositoryItem>(); } } } Writer writer = resp.getWriter(); doc.write(writer); writer.close(); }
From source file:org.orbeon.oxf.transformer.xupdate.TemplatesHandlerImpl.java
License:Open Source License
private Statement[] parseStatements(List nodes) { List statements = new ArrayList(); for (Iterator i = nodes.iterator(); i.hasNext();) { Node node = (Node) i.next(); if (node.getNodeType() == Node.TEXT_NODE) { if (!"".equals(node.getText().trim())) statements.add(new Text(node.getText().trim())); } else if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; NamespaceContext namespaceContext = new SimpleNamespaceContext( Dom4jUtils.getNamespaceContext(element)); if (XUpdateConstants.XUPDATE_NAMESPACE_URI.equals(element.getNamespaceURI())) { if (element.getName().equals("remove")) { statements.add(new Remove((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("update")) { statements// w w w . ja va2 s . c om .add(new Update((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("append")) { statements.add(new Append((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, element.attributeValue("child"), parseStatements(element.content()))); } else if (element.getName().equals("insert-before")) { statements.add( new InsertBefore((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("insert-after")) { statements.add( new InsertAfter((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("for-each")) { statements .add(new ForEach((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("while")) { statements.add(new While((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("value-of")) { statements.add(new ValueOf((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("copy-of")) { statements.add(new CopyOf((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("node-set")) { statements.add(new NodeSet((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("attribute")) { statements.add(new Attribute((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("namespace")) { statements.add(new Namespace((LocationData) element.getData(), element.attributeValue("name"), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("element")) { statements.add(new DynamicElement((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("if")) { statements.add(new If((LocationData) element.getData(), element.attributeValue("test"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("choose")) { List whenTests = new ArrayList(); List whenNamespaceContext = new ArrayList(); List whenStatements = new ArrayList(); for (Iterator j = element.elements("when").iterator(); j.hasNext();) { Element whenElement = (Element) j.next(); whenTests.add(whenElement.attributeValue("test")); whenNamespaceContext .add(new SimpleNamespaceContext(Dom4jUtils.getNamespaceContext(whenElement))); whenStatements.add(parseStatements(whenElement.content())); } Element otherwiseElement = element.element("otherwise"); statements.add(new Choose((LocationData) element.getData(), (String[]) whenTests.toArray(new String[whenTests.size()]), (NamespaceContext[]) whenNamespaceContext .toArray(new NamespaceContext[whenNamespaceContext.size()]), (Statement[][]) whenStatements.toArray(new Statement[whenStatements.size()][]), otherwiseElement == null ? null : parseStatements(otherwiseElement.content()))); } else if (element.getName().equals("variable")) { statements.add(new Variable((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("assign")) { statements.add(new Assign((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("function")) { statements.add(new Function((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("param")) { statements.add(new Param((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("message")) { statements.add( new Message((LocationData) element.getData(), parseStatements(element.content()))); } else if (element.getName().equals("error")) { statements.add( new Error((LocationData) element.getData(), parseStatements(element.content()))); } else { throw new ValidationException( "Unsupported XUpdate element '" + element.getQualifiedName() + "'", (LocationData) element.getData()); } } else { Element staticElement = new NonLazyUserDataElement(element.getQName()); List childNodes = new ArrayList(); for (Iterator j = element.attributes().iterator(); j.hasNext();) staticElement.add((org.dom4j.Attribute) ((org.dom4j.Attribute) j.next()).clone()); for (Iterator j = element.content().iterator(); j.hasNext();) { Node child = (Node) j.next(); if (child instanceof org.dom4j.Namespace) { staticElement.add((Node) child.clone()); } else { childNodes.add(child); } } statements.add(new StaticElement((LocationData) element.getData(), staticElement, parseStatements(childNodes))); } } else if (node.getNodeType() == Node.NAMESPACE_NODE) { // Ignore namespace declarations } else { throw new OXFException("Unsupported node: " + node.getNodeTypeName()); } } return (Statement[]) statements.toArray(new Statement[statements.size()]); }
From source file:org.orbeon.oxf.xforms.action.actions.XFormsInsertAction.java
License:Open Source License
public static List<NodeInfo> doInsert(XFormsContainingDocument containingDocument, IndentedLogger indentedLogger, String positionAttribute, List collectionToBeUpdated, NodeInfo insertContextNodeInfo, List<Item> originItems, int insertionIndex, boolean doClone, boolean doDispatch) { final boolean isEmptyNodesetBinding = collectionToBeUpdated == null || collectionToBeUpdated.size() == 0; // "3. The origin node-set is determined." // "5. Each node in the origin node-set is cloned in the order it appears in the origin node-set." final List<Node> sourceNodes; final List<Node> clonedNodes; {/* w w w . j ava2 s .co m*/ final List<Node> clonedNodesTemp; if (originItems == null) { // There are no explicitly specified origin objects, use node from Node Set Binding node-set // "If the origin attribute is not given and the Node Set Binding node-set is empty, then the origin // node-set is the empty node-set. [...] The insert action is terminated with no effect if the // origin node-set is the empty node-set." if (isEmptyNodesetBinding) { if (indentedLogger != null && indentedLogger.isDebugEnabled()) indentedLogger.logDebug("xf:insert", "origin node-set from node-set binding is empty, terminating"); return Collections.EMPTY_LIST; } // "Otherwise, if the origin attribute is not given, then the origin node-set consists of the last // node of the Node Set Binding node-set." final Node singleSourceNode = XFormsUtils.getNodeFromNodeInfoConvert( (NodeInfo) collectionToBeUpdated.get(collectionToBeUpdated.size() - 1)); // TODO: check namespace handling might be incorrect. Should use copyElementCopyParentNamespaces() instead? final Node singleClonedNode = Dom4jUtils.createCopy(singleSourceNode); sourceNodes = Collections.singletonList(singleSourceNode); clonedNodesTemp = Collections.singletonList(singleClonedNode); } else { // There are explicitly specified origin objects // "The insert action is terminated with no effect if the origin node-set is the empty node-set." if (originItems.size() == 0) { if (indentedLogger != null && indentedLogger.isDebugEnabled()) indentedLogger.logDebug("xf:insert", "origin node-set is empty, terminating"); return Collections.EMPTY_LIST; } // "Each node in the origin node-set is cloned in the order it appears in the origin node-set." sourceNodes = new ArrayList<Node>(originItems.size()); // set to max possible size clonedNodesTemp = new ArrayList<Node>(originItems.size()); for (final Object currentObject : originItems) { if (currentObject instanceof NodeInfo) { // This is the regular case covered by XForms 1.1 / XPath 1.0 // NOTE: Don't clone nodes if doClone == false final Node sourceNode = XFormsUtils.getNodeFromNodeInfoConvert((NodeInfo) currentObject); final Node clonedNode = doClone ? (sourceNode instanceof Element) ? ((Element) sourceNode).createCopy() : (Node) sourceNode.clone() : sourceNode; sourceNodes.add(sourceNode); clonedNodesTemp.add(clonedNode); } else if (currentObject instanceof AtomicValue) { // This is an extension: support sequences containing atomic values // Convert the result to a text node final String stringValue = ((Item) currentObject).getStringValue(); final Text textNode = Dom4jUtils.createText(stringValue); sourceNodes.add(null); // there is no source node for this cloned node, it's a source item clonedNodesTemp.add(textNode); } else throw new IllegalStateException(); } } // Remove instance data from cloned nodes and perform Document node adjustment for (int i = 0; i < clonedNodesTemp.size(); i++) { final Node clonedNodeTemp = clonedNodesTemp.get(i); if (clonedNodeTemp instanceof Element) { // Element node InstanceData.remove(clonedNodeTemp); clonedNodeTemp.detach(); } else if (clonedNodeTemp instanceof Attribute) { // Attribute node InstanceData.remove(clonedNodeTemp); clonedNodeTemp.detach(); } else if (clonedNodeTemp instanceof Document) { // Document node final Element clonedNodeTempRootElement = clonedNodeTemp.getDocument().getRootElement(); if (clonedNodeTempRootElement == null) { // Can be null in rare cases of documents without root element clonedNodesTemp.set(i, null); // we support having a null node further below, so set this to null } else { InstanceData.remove(clonedNodeTempRootElement); // We can never really insert a document into anything at this point, but we assume that this means the root element clonedNodesTemp.set(i, clonedNodeTempRootElement.detach()); } } else { // Other nodes clonedNodeTemp.detach(); } } clonedNodes = clonedNodesTemp; } // "6. The target location of each cloned node or nodes is determined" // "7. The cloned node or nodes are inserted in the order they were cloned at their target location // depending on their node type." // Identify the instance that actually changes final XFormsInstance modifiedInstance; // Find actual insertion point and insert final NodeInfo insertLocationNodeInfo; final List<Node> insertedNodes; final String beforeAfterInto; if (isEmptyNodesetBinding) { // Insert INTO a node // "If the Node Set Binding node-set is not specified or empty, the insert location node is the insert // context node." // "a. If the Node Set Binding node-set is not specified or empty, the target location depends on the // node type of the cloned node. If the cloned node is an attribute, then the target location is before // the first attribute of the insert location node. If the cloned node is not an attribute, then the // target location is before the first child of the insert location node." modifiedInstance = (containingDocument != null) ? containingDocument.getInstanceForNode(insertContextNodeInfo) : null; insertLocationNodeInfo = insertContextNodeInfo; final Node insertLocationNode = XFormsUtils.getNodeFromNodeInfo(insertContextNodeInfo, CANNOT_INSERT_READONLY_MESSAGE); insertedNodes = doInsert(insertLocationNode, clonedNodes, modifiedInstance, doDispatch); beforeAfterInto = "into"; // Normalize text nodes if needed to respect XPath 1.0 constraint { boolean hasTextNode = false; for (Node clonedNode : clonedNodes) { hasTextNode |= clonedNode != null && clonedNode.getNodeType() == Node.TEXT_NODE; } if (hasTextNode) Dom4jUtils.normalizeTextNodes(insertLocationNode); } } else { // Insert BEFORE or AFTER a node insertLocationNodeInfo = (NodeInfo) collectionToBeUpdated.get(insertionIndex - 1); final Node insertLocationNode = XFormsUtils.getNodeFromNodeInfo(insertLocationNodeInfo, CANNOT_INSERT_READONLY_MESSAGE); modifiedInstance = (containingDocument != null) ? containingDocument.getInstanceForNode(insertLocationNodeInfo) : null; final Document insertLocationNodeDocument = insertLocationNode.getDocument(); if (insertLocationNodeDocument != null && insertLocationNodeDocument.getRootElement() == insertLocationNode) { // "c. if insert location node is the root element of an instance, then that instance root element // location is the target location. If there is more than one cloned node to insert, only the // first node that does not cause a conflict is considered." insertedNodes = doInsert(insertLocationNode.getDocument(), clonedNodes, modifiedInstance, doDispatch); beforeAfterInto = positionAttribute; // TODO: ideally normalize to "into document node"? // NOTE: Don't need to normalize text nodes in this case, as no new text node is inserted } else { // "d. Otherwise, the target location is immediately before or after the insert location // node, based on the position attribute setting or its default." if (insertLocationNode.getNodeType() == Node.ATTRIBUTE_NODE) { // Special case for "next to an attribute" // NOTE: In XML, attributes are unordered. dom4j handles them as a list so has order, but // the XForms spec shouldn't rely on attribute order. We could try to keep the order, but it // is harder as we have to deal with removing duplicate attributes and find a reasonable // insertion strategy. // TODO: Don't think we should even do this now in XForms 1.1 insertedNodes = doInsert(insertLocationNode.getParent(), clonedNodes, modifiedInstance, doDispatch); } else { // Other node types final Element parentNode = insertLocationNode.getParent(); final List<Node> siblingElements = Dom4jUtils.content(parentNode); final int actualIndex = siblingElements.indexOf(insertLocationNode); // Prepare insertion of new element final int actualInsertionIndex; if ("before".equals(positionAttribute)) { actualInsertionIndex = actualIndex; } else { // "after" actualInsertionIndex = actualIndex + 1; } // "7. The cloned node or nodes are inserted in the order they were cloned at their target // location depending on their node type." boolean hasTextNode = false; int addIndex = 0; insertedNodes = new ArrayList<Node>(clonedNodes.size()); for (Node clonedNode : clonedNodes) { if (clonedNode != null) {// NOTE: we allow passing some null nodes so we check on null if (!(clonedNode instanceof Attribute || clonedNode instanceof Namespace)) { // Element, text, comment, processing instruction node siblingElements.add(actualInsertionIndex + addIndex, clonedNode); insertedNodes.add(clonedNode); hasTextNode |= clonedNode.getNodeType() == Node.TEXT_NODE; addIndex++; } else { // We never insert attributes or namespace nodes as siblings if (indentedLogger != null && indentedLogger.isDebugEnabled()) indentedLogger.logDebug("xf:insert", "skipping insertion of node as sibling in element content", "type", clonedNode.getNodeTypeName(), "node", clonedNode instanceof Attribute ? Dom4jUtils.attributeToDebugString((Attribute) clonedNode) : clonedNode.toString()); } } } // Normalize text nodes if needed to respect XPath 1.0 constraint if (hasTextNode) Dom4jUtils.normalizeTextNodes(parentNode); } beforeAfterInto = positionAttribute; } } // Whether some nodes were inserted final boolean didInsertNodes = insertedNodes != null && insertedNodes.size() > 0; // Log stuff if (indentedLogger != null && indentedLogger.isDebugEnabled()) { if (didInsertNodes) indentedLogger.logDebug("xf:insert", "inserted nodes", "count", Integer.toString(insertedNodes.size()), "instance", (modifiedInstance != null) ? modifiedInstance.getEffectiveId() : null); else indentedLogger.logDebug("xf:insert", "no node inserted"); } // "XForms Actions that change the tree structure of instance data result in setting all four flags to true" if (didInsertNodes && modifiedInstance != null) { // NOTE: Can be null if document into which delete is performed is not in an instance, e.g. in a variable modifiedInstance.markModified(); modifiedInstance.model().markStructuralChange(modifiedInstance); } // Gather list of modified nodes final List<NodeInfo> insertedNodeInfos; if (didInsertNodes && modifiedInstance != null) { // Can be null if document into which delete is performed is not in an instance, e.g. in a variable final DocumentWrapper documentWrapper = (DocumentWrapper) modifiedInstance.documentInfo(); insertedNodeInfos = new ArrayList<NodeInfo>(insertedNodes.size()); for (Object insertedNode : insertedNodes) insertedNodeInfos.add(documentWrapper.wrap(insertedNode)); } else { insertedNodeInfos = Collections.emptyList(); } // "4. If the insert is successful, the event xforms-insert is dispatched." // XFormsInstance handles index and repeat items updates if (doDispatch && didInsertNodes && modifiedInstance != null) { // Adjust insert location node and before/after/into in case the root element was replaced final NodeInfo adjustedInsertLocationNodeInfo; final String adjustedBeforeAfterInto; final NodeInfo parent = insertedNodeInfos.get(0).getNodeKind() == org.w3c.dom.Node.ELEMENT_NODE ? insertedNodeInfos.get(0).getParent() : null; if (parent != null && parent.equals(parent.getDocumentRoot())) { // Node was inserted under document node adjustedInsertLocationNodeInfo = parent.getDocumentRoot(); adjustedBeforeAfterInto = "into"; } else { adjustedInsertLocationNodeInfo = insertLocationNodeInfo; adjustedBeforeAfterInto = beforeAfterInto; } Dispatch.dispatchEvent(new XFormsInsertEvent(modifiedInstance, insertedNodeInfos, originItems, adjustedInsertLocationNodeInfo, adjustedBeforeAfterInto)); } return insertedNodeInfos; }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Convert a dom4j node to a string./*w w w .j a v a 2s . c o m*/ * * @param node node to convert * @return resulting string */ public static String nodeToString(final Node node) { final String ret; switch (node.getNodeType()) { case Node.DOCUMENT_NODE: { ret = domToString((Branch) ((Document) node).getRootElement()); break; } case Node.ELEMENT_NODE: { ret = domToString((Branch) node); break; } case Node.TEXT_NODE: { ret = node.getText(); break; } default: ret = domToString(node, null); break; } return ret; }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Removes the elements and text inside the given element, but not the attributes or namespace * declarations on the element./*from ww w.j av a 2 s . c o m*/ */ public static void clearElementContent(final Element elt) { final java.util.List cntnt = elt.content(); for (final java.util.ListIterator j = cntnt.listIterator(); j.hasNext();) { final Node chld = (Node) j.next(); if (chld.getNodeType() == Node.TEXT_NODE || chld.getNodeType() == Node.ELEMENT_NODE) { j.remove(); } } }
From source file:org.xwiki.tool.xar.XWikiXMLWriter.java
License:Open Source License
@Override protected void writeNodeText(Node node) throws IOException { if (this.useFormat && node.getText().trim().length() == 0) { // Check if parent node contains non text nodes boolean containsNonTextNode = false; for (Object object : node.getParent().content()) { Node objectNode = (Node) object; if (objectNode.getNodeType() != Node.TEXT_NODE) { containsNonTextNode = true; break; }//w ww . java2 s. c o m } if (containsNonTextNode) { // Don't do anything, i.e. don't print the current text node } else { super.writeNodeText(node); } } else { super.writeNodeText(node); } }
From source file:org.zenonpagetemplates.onePhaseImpl.PageTemplateImpl.java
License:Open Source License
@SuppressWarnings({ "unchecked" }) private void defaultContent(Element element, ContentHandler contentHandler, LexicalHandler lexicalHandler, EvaluationHelper evaluationHelper, Stack<Map<String, Slot>> slotStack) throws SAXException, PageTemplateException, IOException, EvaluationException { // Use default template content for (Iterator<Node> i = element.nodeIterator(); i.hasNext();) { Node node = i.next();// w ww. j a v a 2 s. c o m switch (node.getNodeType()) { case Node.ELEMENT_NODE: processElement((Element) node, contentHandler, lexicalHandler, evaluationHelper, slotStack); break; case Node.TEXT_NODE: char[] text = node.getText().toCharArray(); contentHandler.characters(text, 0, text.length); break; case Node.COMMENT_NODE: char[] comment = node.getText().toCharArray(); lexicalHandler.comment(comment, 0, comment.length); break; case Node.CDATA_SECTION_NODE: lexicalHandler.startCDATA(); char[] cdata = node.getText().toCharArray(); contentHandler.characters(cdata, 0, cdata.length); lexicalHandler.endCDATA(); break; case Node.NAMESPACE_NODE: Namespace declared = (Namespace) node; //System.err.println( "Declared namespace: " + declared.getPrefix() + ":" + declared.getURI() ); this.namespaces.put(declared.getPrefix(), declared.getURI()); //if ( declared.getURI().equals( TAL_NAMESPACE_URI ) ) { // this.talNamespacePrefix = declared.getPrefix(); //} //else if (declared.getURI().equals( METAL_NAMESPACE_URI ) ) { // this.metalNamespacePrefix = declared.getPrefix(); //} break; case Node.ATTRIBUTE_NODE: // Already handled break; case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: default: //System.err.println( "WARNING: Node type not supported: " + node.getNodeTypeName() ); } } }
From source file:org.zenonpagetemplates.twoPhasesImpl.ZPTDocumentFactory.java
License:Open Source License
@SuppressWarnings({ "unchecked" }) static private void mapContent(Element element, ZPTElement zptElement, ZPTDocument zptDocument, Stack<Map<String, Slot>> slotStack) throws SAXException, PageTemplateException, IOException { // Use default template content for (Iterator<Node> i = element.nodeIterator(); i.hasNext();) { Node node = i.next();/*from w w w . j a v a2s . c o m*/ switch (node.getNodeType()) { case Node.ELEMENT_NODE: zptElement.addContent(getNewZPTElement((Element) node, zptDocument, slotStack)); break; case Node.TEXT_NODE: zptElement.addContent(new TextNode(node.getText())); break; case Node.CDATA_SECTION_NODE: zptElement.addContent(new CDATANode(node.getText())); break; case Node.NAMESPACE_NODE: // Already handled /* Namespace declared = (Namespace)node; if (zptDocument.isNamespaceToDeclare(declared)){ zptDocument.addNamespace(declared); } else { zptElement.addNamespaceStaticAttribute(declared); } break;*/ case Node.ATTRIBUTE_NODE: // Already handled case Node.COMMENT_NODE: // Remove all comments case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: default: // Nothing to do } } }