Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.apache.airavata.gfac.core.GFacUtils.java

public static List<Element> getElementList(Document doc, String expression) throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression expr = xPath.compile(expression);
    NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    List<Element> elementList = new ArrayList<Element>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node item = nodeList.item(i);
        if (item instanceof Element) {
            elementList.add((Element) item);
        }//from   www . j av a2s.co  m
    }
    return elementList;
}

From source file:org.apache.ode.bpel.compiler.v1.xpath10.jaxp.JaxpXPath10ExpressionCompilerImpl.java

/**
 * Verifies validity of a xpath expression.
 *///from w  w  w . j  a va2 s.c o  m
protected void doJaxpCompile(OXPath10Expression out, Expression source) throws CompilationException {
    String xpathStr;
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XPath string and xpath node are both null");
    }

    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.errXPathSyntax(xpathStr));
    }

    try {
        __log.debug("JAXP compile: xpath = " + xpathStr);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP compile: XPathFactory impl = " + xpf.getClass());
        XPath xpath = xpf.newXPath();
        xpath.setXPathFunctionResolver(
                new JaxpFunctionResolver(_compilerContext, out, source.getNamespaceContext(), _bpelNsURI));
        xpath.setXPathVariableResolver(new JaxpVariableResolver(_compilerContext, out));
        xpath.setNamespaceContext(source.getNamespaceContext());
        XPathExpression xpe = xpath.compile(xpathStr);
        // dummy evaluation to resolve variables and functions (hopefully complete...)
        xpe.evaluate(DOMUtils.newDocument());
        out.xpath = xpathStr;
    } catch (XPathExpressionException e) {
        throw new CompilationException(__msgs.errUnexpectedCompilationError(e.getMessage()), e);
    }
}

From source file:org.apache.ode.bpel.compiler.v1.xpath20.XPath20ExpressionCompilerImpl.java

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;/*from w  w w  .java  2  s . c om*/
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XPath string and xpath node are both null");
    }
    if (node.getNodeType() != Node.TEXT_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    out.xpath = xpathStr;
    try {
        __log.debug("Compiling expression " + xpathStr);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(_compilerContext, out);
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(source.getNamespaceContext());
        XPathExpression expr = xpe.compile(xpathStr);
        // evaluate the expression so as to initialize the variables
        try {
            expr.evaluate(node);
        } catch (XPathExpressionException xpee) {
            // swallow errors caused by uninitialized variable 
        }
        for (String varExpr : extractVariableExprs(xpathStr)) {
            expr = xpe.compile(varExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable 
            }
        }
    } catch (XPathFactoryConfigurationException xpfce) {
        __log.debug(xpfce);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (XPathExpressionException e) {
        __log.debug(e);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.compiler.XPath20ExpressionCompilerImpl.java

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;// w ww .  ja v  a2s.  c o  m
    Node node = source.getExpression();
    if (node == null) {
        throw new CompilationException(__msgs.errEmptyExpression(source.getURI(),
                new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    out.xpath = xpathStr;
    try {
        __log.debug("Compiling expression " + xpathStr);
        XPathFactory xpf = new XPathFactoryImpl();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(_compilerContext, out);
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(source.getNamespaceContext());
        XPathExpression expr = xpe.compile(xpathStr);
        // evaluate the expression so as to initialize the variables
        try {
            expr.evaluate(node);
        } catch (XPathExpressionException xpee) {
            // swallow errors caused by uninitialized variable
        }
        for (String varExpr : extractVariableExprs(xpathStr)) {
            expr = xpe.compile(varExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
        for (String functionExpr : extractFunctionExprs(xpathStr)) {
            expr = xpe.compile(functionExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
    } catch (XPathExpressionException e) {
        __log.debug(e);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.rtrep.v1.xpath10.jaxp.JaxpXPath10ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {/*from  w w w  .ja  v a2  s. c  o m*/
        OXPath10Expression oxpath = (OXPath10Expression) cexp;
        __log.debug("JAXP runtime: evaluating " + oxpath.xpath);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP runtime: XPathFactory impl = " + xpf.getClass());
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath));
        xpe.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath));
        xpe.setNamespaceContext(oxpath.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Object evalResult = expr
                .evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }

}

From source file:org.apache.ode.bpel.rtrep.v1.xpath20.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {/*  w  w  w.ja  v  a  2s . co  m*/
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        // JAXP based XPath 1.0 runtime does not work anymore after a XPath 2.0 has been evaluated if this is set.
        // System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
        //        "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) xpf).getConfiguration());
        xpf.setXPathFunctionResolver(funcResolver);
        xpf.setXPathVariableResolver(varResolver);
        XPath xpe = xpf.newXPath();
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Node contextNode = ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode();
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof DynamicError) {
            Throwable th = ((DynamicError) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }
}

From source file:org.apache.ode.bpel.rtrep.v2.xpath20.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {//from  w  w  w .  j a  v a  2  s  . com
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        // JAXP based XPath 1.0 runtime does not work anymore after a XPath 2.0 has been evaluated if this is set.
        // System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
        //        "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) xpf).getConfiguration());
        xpf.setXPathFunctionResolver(funcResolver);
        xpf.setXPathVariableResolver(varResolver);
        XPath xpe = xpf.newXPath();
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Node contextNode = ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode();
        // Create step nodes in XPath in case it is incompletely instantiated 
        if (oxpath20.insertMissingData) {
            XPath20ExpressionModifier modifier = new XPath20ExpressionModifier(oxpath20.namespaceCtx,
                    ((XPathFactoryImpl) xpf).getConfiguration().getNamePool());
            Node temp = ctx.getRootNode();
            if (temp.getLocalName().equals("message") && temp.getNamespaceURI() == null
                    && temp.getFirstChild() != null && temp.getFirstChild().getFirstChild() != null) {
                modifier.insertMissingData(expr, temp.getFirstChild().getFirstChild());
            } else {
                modifier.insertMissingData(expr, temp);
            }
        }

        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof DynamicError) {
            Throwable th = ((DynamicError) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }

}

From source file:org.apache.syncope.console.commons.XMLRolesReader.java

/**
 * Get all roles allowed for specific page and action requested.
 *
 * @param pageId/*  ww w .j a v  a 2s  .c o  m*/
 * @param actionId
 * @return roles list comma separated
 */
public String getAllAllowedRoles(final String pageId, final String actionId) {
    if (doc == null) {
        return StringUtils.EMPTY;
    }

    final StringBuilder roles = new StringBuilder();
    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(
                "//page[@id='" + pageId + "']/" + "action[@id='" + actionId + "']/" + "entitlement/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            if (i > 0) {
                roles.append(",");
            }
            roles.append(nodes.item(i).getNodeValue());
        }
    } catch (XPathExpressionException e) {
        LOG.error("While parsing authorizations file", e);
    }

    LOG.debug("Authorizations found: {}", roles);

    return roles.toString();
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
 * Return true if the passed in node or any downstream (higher index)
 * siblings <strong>relative to its destination location</strong> have
 * moveAllowed="false"./*from w  w w  .  j a  v a 2s  .  c  o  m*/
 */
private static boolean isNotReparentable(NodeInfo ni, Element compViewParent, Element positionSet) {

    // This one is easy -- can't re-parent a node with dlm:moveAllowed=false
    if (ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
        return true;
    }

    try {
        /*
         *  Annoying to do in Java, but we need to find our own placeholder
         *  element in the positionSet
         */
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni.getId() + "']";
        final XPathExpression findPlaceholder = xpath.compile(findPlaceholderXpath);
        final NodeList findPlaceholderList = (NodeList) findPlaceholder.evaluate(positionSet,
                XPathConstants.NODESET);
        switch (findPlaceholderList.getLength()) {
        case 0:
            LOG.warn("Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet="
                    + XmlUtilitiesImpl.toString(positionSet));
            return true;
        case 1:
            // This is healthy
            break;
        default:
            LOG.warn("More than one node found for XPathExpression=\"" + findPlaceholderXpath
                    + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
            return true;
        }
        final Element placeholder = (Element) findPlaceholderList.item(0); // At last

        for (Element nextPlaceholder = (Element) placeholder.getNextSibling(); // Start with the next dlm:position element after placeholder
                nextPlaceholder != null; // As long as we have a placeholder to look at
                nextPlaceholder = (Element) nextPlaceholder.getNextSibling()) { // Advance to the next placeholder

            if (LOG.isDebugEnabled()) {
                LOG.debug("Considering whether node ''" + ni.getId()
                        + "' is Reparentable;  subsequent sibling is:  "
                        + nextPlaceholder.getAttribute("name"));
            }

            /*
             * Next task:  we have to find the non-placeholder representation of
             * the nextSiblingPlaceholder within the compViewParent
             */
            final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder.getAttribute("name") + "']";
            final XPathExpression unmaskPlaceholder = xpath.compile(unmaskPlaceholderXpath);
            final NodeList unmaskPlaceholderList = (NodeList) unmaskPlaceholder.evaluate(compViewParent,
                    XPathConstants.NODESET);
            switch (unmaskPlaceholderList.getLength()) {
            case 0:
                // Not a problem;  the nextSiblingPlaceholder also refers
                // to a node that has been moved to this context (afaik)
                continue;
            case 1:
                final Element nextSibling = (Element) unmaskPlaceholderList.item(0);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Considering whether node ''" + ni.getId()
                            + "' is Reparentable;  subsequent sibling '" + nextSibling.getAttribute("ID")
                            + "' has dlm:moveAllowed="
                            + !nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false"));
                }

                // Need to perform some checks...
                if (nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {

                    /*
                     *  The following check is a bit strange;  it seems to verify
                     *  that the current NodeInfo and the nextSibling come from the
                     *  same fragment.  If they don't, the re-parenting is allowable.
                     *  I believe this check could only be unsatisfied in the case
                     *  of tabs.
                     */
                    Precedence p = Precedence.newInstance(nextSibling.getAttribute(Constants.ATT_FRAGMENT));
                    if (ni.getPrecedence().isEqualTo(p)) {
                        return true;
                    }
                }
                break;
            default:
                LOG.warn("More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath
                        + "\" in compViewParent");
                return true;
            }
        }
    } catch (XPathExpressionException xpe) {
        throw new RuntimeException("Failed to evaluate XPATH", xpe);
    }

    return false; // Re-parenting is "not disallowed" (double-negative less readable)

}

From source file:org.apereo.portal.layout.dlm.remoting.UpdatePreferencesServlet.java

/**
 * Subscribe a user to a pre-formatted tab (pulled DLM fragment).
 *
 * @param request//w w  w  . j  av  a  2 s.c  o  m
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=subscribeToTab")
public ModelAndView subscribeToTab(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);
    IPerson per = getPerson(ui, response);

    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();

    // Get the fragment owner's name from the request and construct
    // an IPerson object representing that user
    String fragmentOwnerName = request.getParameter("sourceID");
    if (StringUtils.isBlank(fragmentOwnerName)) {
        logger.warn("Attempted to subscribe to tab with null owner ID");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("jsonView",
                Collections.singletonMap("error", "Attempted to subscribe to tab with null owner ID"));
    }
    RestrictedPerson fragmentOwner = PersonFactory.createRestrictedPerson();
    fragmentOwner.setUserName(fragmentOwnerName);

    // Mark the currently-authenticated user as subscribed to this fragment.
    // If an inactivated fragment registration already exists, update it
    // as an active subscription.  Otherwise, create a new fragment
    // subscription.
    IUserFragmentSubscription userFragmentInfo = userFragmentInfoDao.getUserFragmentInfo(per, fragmentOwner);
    if (userFragmentInfo == null) {
        userFragmentInfo = userFragmentInfoDao.createUserFragmentInfo(per, fragmentOwner);
    } else {
        userFragmentInfo.setActive(true);
        userFragmentInfoDao.updateUserFragmentInfo(userFragmentInfo);
    }

    try {
        // reload user layout and stylesheet to incorporate new DLM fragment
        ulm.loadUserLayout(true);

        // get the target node this new tab should be moved after
        String destinationId = request.getParameter("elementID");

        // get the user layout for the currently-authenticated user
        int uid = userIdentityStore.getPortalUID(fragmentOwner, false);
        final DistributedUserLayout userLayout = userLayoutStore.getUserLayout(per, upm.getUserProfile());
        Document layoutDocument = userLayout.getLayout();

        // attempt to find the new subscribed tab in the layout so we can
        // move it
        StringBuilder expression = new StringBuilder("//folder[@type='root']/folder[starts-with(@ID,'")
                .append(Constants.FRAGMENT_ID_USER_PREFIX).append(uid).append("')]");
        XPathFactory fac = XPathFactory.newInstance();
        XPath xpath = fac.newXPath();
        NodeList nodes = (NodeList) xpath.evaluate(expression.toString(), layoutDocument,
                XPathConstants.NODESET);
        String sourceId = nodes.item(0).getAttributes().getNamedItem("ID").getTextContent();
        ulm.moveNode(sourceId, ulm.getParentId(destinationId), destinationId);

        ulm.saveUserLayout();

        return new ModelAndView("jsonView", Collections.singletonMap("tabId", sourceId));

    } catch (XPathExpressionException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return new ModelAndView("jsonView", Collections.singletonMap("error", "Xpath error"));
    } catch (PortalException e) {
        return handlePersistError(request, response, e);
    }

}