Example usage for org.dom4j Node detach

List of usage examples for org.dom4j Node detach

Introduction

In this page you can find the example usage for org.dom4j Node detach.

Prototype

Node detach();

Source Link

Document

Removes this node from its parent if there is one.

Usage

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

License:Open Source License

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);//w w w.  j  av  a2s  .c  o  m

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.transformer.xupdate.statement.Remove.java

License:Open Source License

public Object execute(URIResolver uriResolver, Object context, VariableContextImpl variableContext,
        DocumentContext documentContext) {
    for (Iterator i = Utils.evaluateToList(uriResolver, context, variableContext, getLocationData(), select,
            namespaceContext, documentContext).iterator(); i.hasNext();) {
        Node node = (Node) i.next();
        node.detach();
    }// ww  w.j av a 2 s  .c  o  m
    return Collections.EMPTY_LIST;
}

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;
    {//from  www.j a va2  s  .  c  om
        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

/**
 * Go over the Node and its children and make sure that there are no two contiguous text nodes so as to ensure that
 * XPath expressions run correctly. As per XPath 1.0 (http://www.w3.org/TR/xpath):
 *
 * "As much character data as possible is grouped into each text node: a text node never has an immediately
 * following or preceding sibling that is a text node."
 *
 * dom4j Text and CDATA nodes are combined together.
 *
 * @param nodeToNormalize Node hierarchy to normalize
 * @return                the input node, normalized
 *//*from  www .j av  a  2 s.  com*/
public static Node normalizeTextNodes(Node nodeToNormalize) {
    final List<Node> nodesToDetach = new ArrayList<Node>();
    nodeToNormalize.accept(new VisitorSupport() {
        public void visit(Element element) {
            final List children = element.content();
            Node previousNode = null;
            StringBuilder sb = null;
            for (Iterator i = children.iterator(); i.hasNext();) {
                final Node currentNode = (Node) i.next();
                if (previousNode != null) {
                    if (isTextOrCDATA(previousNode) && isTextOrCDATA(currentNode)) {
                        final CharacterData previousNodeText = (CharacterData) previousNode;
                        if (sb == null)
                            sb = new StringBuilder(previousNodeText.getText());
                        sb.append(currentNode.getText());
                        nodesToDetach.add(currentNode);
                    } else if (isTextOrCDATA(previousNode)) {
                        // Update node if needed
                        if (sb != null) {
                            previousNode.setText(sb.toString());
                        }
                        previousNode = currentNode;
                        sb = null;
                    } else {
                        previousNode = currentNode;
                        sb = null;
                    }
                } else {
                    previousNode = currentNode;
                    sb = null;
                }
            }
            // Update node if needed
            if (previousNode != null && sb != null) {
                previousNode.setText(sb.toString());
            }
        }
    });
    // Detach nodes only in the end so as to not confuse the acceptor above
    for (final Node currentNode : nodesToDetach) {
        currentNode.detach();
    }

    return nodeToNormalize;
}

From source file:org.pentaho.actionsequence.dom.ActionSequenceDocument.java

License:Open Source License

/**
 * Sets the action sequence result type/*from  www  . ja  va2  s . c  o m*/
 * 
 * @param value
 *          the result type
 */
public void setResultType(String value) {
    Element actSeq = (Element) document.selectSingleNode(ACTION_SEQUENCE);
    if (value == null) {
        Node subElement = actSeq.selectSingleNode(ACTION_SEQUENCE_DOCUMENTATION_RESULT_TYPE);
        if (subElement != null) {
            subElement.detach();
            fireHeaderChanged(this);
        }
    } else {
        Element subElement = DocumentHelper.makeElement(actSeq, ACTION_SEQUENCE_DOCUMENTATION_RESULT_TYPE);
        subElement.setText(value == null ? "" : value); //$NON-NLS-1$
        fireHeaderChanged(this);
    }
}

From source file:org.pentaho.common.ui.services.SolutionRepoService.java

License:Open Source License

/**
 * Saves state into the solution repository
 *//*from   w w w  . j  a v  a 2 s.  c om*/
protected StateMessage saveState(String filepath, String state, boolean stateIsXml, String type,
        Boolean replace, String title, String description) throws Exception {

    StateMessage result = new StateMessage();

    result.setStatus(StateMessage.STATUS_FAILED);
    if (StringUtils.isEmpty(filepath)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0001_NO_FILEPATH")); //$NON-NLS-1$
        return result;
    }
    if (StringUtils.isEmpty(state)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0002_NO_STATE")); //$NON-NLS-1$
        return result;
    }
    if (StringUtils.isEmpty(type)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0007_NO_TYPE")); //$NON-NLS-1$
        return result;
    }
    if (replace == null) {
        replace = Boolean.FALSE;
        //      return result;
    }

    // make sure the path is good
    ActionInfo info = ActionInfo.parseActionString(filepath);
    if (info == null) {
        result.setMessage(
                Messages.getErrorString("SolutionUrlContentGenerator.ERROR_0005_BAD_FILEPATH", filepath)); //$NON-NLS-1$
        return result;
    }

    IPentahoSession userSession = PentahoSessionHolder.getSession();
    ISolutionRepository repo = PentahoSystem.get(ISolutionRepository.class, userSession);

    // create the state file to save
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("state-file"); //$NON-NLS-1$
    Element documentation = root.addElement("documentation"); //$NON-NLS-1$
    documentation.addElement("author").addCDATA(userSession.getName()); //$NON-NLS-1$

    if (stateIsXml) {
        Element stateElement = root.addElement("state-xml"); //$NON-NLS-1$
        Document stateDoc = null;
        try {
            stateDoc = DocumentHelper.parseText(state);
        } catch (Exception e) {
            result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0009_BAD_STATE", state)); //$NON-NLS-1$
            return result;
        }
        Node stateRoot = stateDoc.getRootElement();
        stateRoot = stateRoot.detach();
        stateElement.add(stateRoot);
    } else {
        Element stateElement = root.addElement("state-text"); //$NON-NLS-1$
        stateElement.addCDATA(state);
    }

    documentation.addElement("title").addCDATA(title); //$NON-NLS-1$
    documentation.addElement("description").addCDATA(description); //$NON-NLS-1$

    String fileName = info.getActionName();
    if (!fileName.endsWith('.' + type)) {
        fileName = fileName + '.' + type;
    }

    // see if we can find a content generator to get the file icon
    IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, userSession);
    if (pluginManager != null) {
        //      IContentInfo contentInfo = pluginManager.getContentInfoFromExtension(type, userSession);
        IContentInfo contentInfo = pluginManager.getContentTypeInfo(type);
        if (contentInfo != null) {
            String icon = contentInfo.getIconUrl();
            documentation.addElement("icon").addCDATA(icon); //$NON-NLS-1$
        }
    }

    String basePath = PentahoSystem.getApplicationContext().getSolutionRootPath();
    if (!basePath.endsWith("" + ISolutionRepository.SEPARATOR)) { //$NON-NLS-1$
        basePath = basePath + ISolutionRepository.SEPARATOR;
    }
    // save the file
    int ret = repo.addSolutionFile(basePath, info.getSolutionName() + '/' + info.getPath(), fileName,
            doc.asXML().getBytes(), replace);

    if (ret == ISolutionRepository.FILE_EXISTS) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0004_CANNOT_REPLACE")); //$NON-NLS-1$
        return result;
    } else if (ret == ISolutionRepository.FILE_ADD_INVALID_USER_CREDENTIALS) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0005_CREDENTIALS")); //$NON-NLS-1$
        return result;
    } else if (ret != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0006_SAVE_FAILED")); //$NON-NLS-1$
        return result;
    }

    result.setStatus(StateMessage.STATUS_SUCCESS);
    result.setMessage(Messages.getString("SolutionRepo.USER_FILE_SAVE")); //$NON-NLS-1$
    return result;
}

From source file:org.pentaho.platform.web.servlet.PentahoXmlaServlet.java

License:Open Source License

@Override
protected RepositoryContentFinder makeContentFinder(String dataSourcesUrl) {
    // It is safe to cache these for now because their lambda doesn't
    // do anything with security.
    // BEWARE before making modifications that check security rights or all
    // other kind of stateful things.
    @SuppressWarnings("rawtypes")
    Set keys = cacheMgr.getAllKeysFromRegionCache(CACHE_REGION);

    if (!keys.contains(dataSourcesUrl)) {
        cacheMgr.putInRegionCache(CACHE_REGION, dataSourcesUrl, new DynamicContentFinder(dataSourcesUrl) {
            @Override/*  w w w  .j  av  a 2  s . c o m*/
            public String getContent() {
                try {
                    String original = generateInMemoryDatasourcesXml();
                    EntityResolver loader = new PentahoEntityResolver();
                    Document originalDocument = XmlDom4JHelper.getDocFromString(original, loader);
                    if (PentahoXmlaServlet.logger.isDebugEnabled()) {
                        PentahoXmlaServlet.logger.debug(Messages.getInstance()
                                .getString("PentahoXmlaServlet.DEBUG_ORIG_DOC", originalDocument.asXML())); //$NON-NLS-1$
                    }
                    Document modifiedDocument = (Document) originalDocument.clone();
                    List<Node> nodesToRemove = getNodesToRemove(modifiedDocument);
                    if (PentahoXmlaServlet.logger.isDebugEnabled()) {
                        PentahoXmlaServlet.logger.debug(
                                Messages.getInstance().getString("PentahoXmlaServlet.DEBUG_NODES_TO_REMOVE", //$NON-NLS-1$
                                        String.valueOf(nodesToRemove.size())));
                    }
                    for (Node node : nodesToRemove) {
                        node.detach();
                    }
                    if (PentahoXmlaServlet.logger.isDebugEnabled()) {
                        PentahoXmlaServlet.logger.debug(Messages.getInstance()
                                .getString("PentahoXmlaServlet.DEBUG_MOD_DOC", modifiedDocument.asXML())); //$NON-NLS-1$
                    }
                    return modifiedDocument.asXML();
                } catch (XmlParseException e) {
                    PentahoXmlaServlet.logger.error(Messages.getInstance()
                            .getString("PentahoXmlaServlet.ERROR_0004_UNABLE_TO_GET_DOCUMENT_FROM_STRING"), e); //$NON-NLS-1$
                    return null;
                }
            }

            private List<Node> getNodesToRemove(Document doc) {
                List<Node> nodesToRemove = doc.selectNodes("/DataSources/DataSource/Catalogs/Catalog");
                CollectionUtils.filter(nodesToRemove, new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        Element el = ((DefaultElement) o).element("DataSourceInfo");

                        if (el == null || el.getText() == null || el.getTextTrim().length() == 0) {
                            throw new XmlaException(SERVER_FAULT_FC, UNKNOWN_ERROR_CODE, UNKNOWN_ERROR_FAULT_FS,
                                    new MondrianException("DataSourceInfo not defined for "
                                            + ((DefaultElement) o).attribute("name").getText()));
                        }
                        return el.getText().matches("(?i).*EnableXmla=['\"]?false['\"]?");
                    }
                });
                return nodesToRemove;
            }
        });
    }
    return (RepositoryContentFinder) cacheMgr.getFromRegionCache(CACHE_REGION, dataSourcesUrl);
}

From source file:org.springfield.lou.util.NodeObserver.java

License:Open Source License

public Document get(String xpath) {
    System.out.println("NodeObserver.get(" + xpath + ")");
    List<Node> results = xml.selectNodes(xpath);
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("fsxml");
    for (Iterator<Node> i = results.iterator(); i.hasNext();) {
        Node el = (Node) i.next().clone();
        el.detach();
        root.add(el);/*  www .j a  va  2s.c o m*/
    }
    return doc;
}

From source file:org.springfield.lou.util.NodeObserver.java

License:Open Source License

public void setOrder(Comparator<Node> sorting, OrderDirection direction) {
    System.out.println("NodeObserver.setOrder(" + sorting + "," + direction + ")");
    List<Node> results = xml.selectNodes("/fsxml/*");
    System.out.println("RESULTS: " + results.size());
    Collections.sort(results, sorting);
    if (direction.equals(OrderDirection.DESC)) {
        System.out.println("SORT DESCENDING");
        Collections.sort(results, Collections.reverseOrder(sorting));
    } else {/*  www.j a  v a 2s .c o  m*/
        System.out.println("SORT ASCENDING");
        Collections.sort(results, sorting);
    }
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("fsxml");
    for (Iterator<Node> i = results.iterator(); i.hasNext();) {
        Node el = (Node) i.next().clone();
        el.detach();
        root.add(el);
    }
    xml = doc;
}

From source file:org.withinsea.izayoi.commons.dom.DOMUtils.java

License:Mozilla Public License

public static Node replaceBy(Node node, Node newNode) throws InvocationTargetException, IllegalAccessException {
    insertBefore(newNode, node);/*from w  w w .jav a2 s .  c o  m*/
    node.detach();
    return newNode;
}