Example usage for org.apache.commons.jxpath JXPathContext selectSingleNode

List of usage examples for org.apache.commons.jxpath JXPathContext selectSingleNode

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext selectSingleNode.

Prototype

public Object selectSingleNode(String xpath) 

Source Link

Document

Finds the first object that matches the specified XPath.

Usage

From source file:de.innovationgate.wgpublisher.hdb.HDBModel.java

private Filter getFilterNode(Document baseModel, String targetClass, String filter) {

    if (!(baseModel instanceof DocumentParent)) {
        return null;
    }//from w w  w .  j  a  v a  2s . c o m

    Document model = findChildModelOfClass((DocumentParent) baseModel, targetClass);
    JXPathContext jxPath = JXPathContext.newContext(model);

    return (Filter) jxPath.selectSingleNode("/filters[name='" + filter + "']");

}

From source file:de.innovationgate.wgpublisher.hdb.HDBModel.java

/**
 * Retrieve the valid relation targets for a HDBModel relation
 * @param content The content having the relation or a parent content below which the model of this content is defined (in case the content does not yet exist)
 * @param contentClass The content class of the content for which the relation is defined
 * @param relation Name of the relation//from   w  w  w  .j  av  a 2s .co  m
 * @param options Custom options for the retrieval. Use constants OPTION_... from this class or QUERYOPTION_... from {@link WGDatabase}
 * @return Result set of all valid relation targets 
 * @throws WGException
 * @throws HDBModelException
 */
@CodeCompletion
public WGAbstractResultSet getRelationTargets(WGContent content, String contentClass, String relation,
        Map options) throws WGException, HDBModelException {

    Document refNode = getModelForContent(content);
    if (refNode == null) {
        throw new HDBModelException("Cannot find model for content " + content.getContentKey() + " of class "
                + content.getContentClass());
    }

    Content contentNode = null;
    if (refNode instanceof Content
            && (contentClass == null || contentClass.equals(((Content) refNode).getContentClass()))) {
        contentNode = (Content) refNode;
    } else if (refNode instanceof DocumentParent) {
        contentNode = findChildModelOfClass((DocumentParent) refNode, contentClass);
        if (contentNode == null) {
            throw new HDBModelException(
                    "Cannot find direct child content class " + contentClass + " from ref document '"
                            + content.getContentKey() + "' of class " + content.getContentClass());
        }
    }

    JXPathContext jxPath = JXPathContext.newContext(contentNode);
    Relation relationNode = (Relation) jxPath.selectSingleNode("/relations[name='" + relation + "']");
    if (relationNode == null) {
        throw new HDBModelException(
                "Cannot find relation '" + relation + "' for content class " + content.getContentClass());
    }

    String extraClause = (String) options.get(OPTION_EXTRACLAUSE);
    Map extraParams = (Map) options.get(OPTION_EXTRAPARAMS);
    if (extraParams != null) {
        extraParams = new HashMap(extraParams);
    }
    Boolean includeCurrent = WGUtils.getBooleanMapValue(options, OPTION_INCLUDECURRENT, true);

    return getRelationTargets(content, contentClass, relationNode, extraClause, extraParams, includeCurrent,
            options);

}

From source file:de.innovationgate.wgpublisher.hdb.HDBModel.java

/**
 * Retrieves the source contents for a HDBModel relation that point to a given content
 * @param target The content to which the relations point
 * @param contentClass The content class of the source contents to return. Specify null to return contents of all content classes.
 * @param relation The name of the relation that should point to the target content
 * @param options Custom options for the retrieval. Use constants OPTION_... from this class or QUERYOPTION_... from {@link WGDatabase} 
 * @throws WGAPIException//from w  w w .j a v a  2 s . c  o  m
 * @throws HDBModelException
 */
@CodeCompletion
public WGAbstractResultSet getRelationSources(WGContent target, String contentClass, String relation,
        Map options) throws WGAPIException, HDBModelException {

    String extraClause = (String) options.get(OPTION_EXTRACLAUSE);

    Map extraParams = (Map) options.get(OPTION_EXTRAPARAMS);

    JXPathContext jxPath = JXPathContext.newContext(_definition);
    Relation relationNode = (Relation) jxPath.selectSingleNode(
            "//childContents[contentClass='" + contentClass + "']/relations[name='" + relation + "']");
    if (relationNode == null) {
        throw new HDBModelException(
                "Cannot find relation '" + relation + "' for content class " + contentClass);
    }

    StringBuffer hql = new StringBuffer();
    if (relationNode.isGroup()) {
        hql.append(
                "content.contentclass = :contentclass and :target in (select rel.target from ContentRelation as rel where rel.parentcontent = content and rel.group=:relname)");
    } else {
        hql.append("content.contentclass = :contentclass and content.relations[:relname].target = :target");
    }
    if (extraClause != null) {
        // Extract an optional order by clause from the extra clause
        String extraClauseOrderClause = null;
        int whereClauseEndIdx = extraClause.toLowerCase().indexOf("order by");
        if (whereClauseEndIdx != -1) {
            extraClauseOrderClause = extraClause.substring(whereClauseEndIdx + 8);
            extraClause = extraClause.substring(0, whereClauseEndIdx);
        }
        if (!extraClause.trim().isEmpty()) {
            hql.append(" AND (" + extraClause + ")");
        }
        if (extraClauseOrderClause != null) {
            hql.append(" ORDER BY ").append(extraClauseOrderClause);
        }
    }

    Map queryParams = new HashMap();
    queryParams.put("contentclass", contentClass);
    queryParams.put("relname", relation);
    queryParams.put("target", target);
    if (extraParams != null) {
        queryParams.putAll(extraParams);
    }

    Map parameters = new HashMap();
    parameters.put(WGDatabase.QUERYOPTION_QUERY_PARAMETERS, queryParams);

    // Transport regular query parameters to the internal query
    migrateQueryParameter(WGDatabase.QUERYOPTION_CACHERESULT, options, queryParams);
    migrateQueryParameter(WGDatabase.QUERYOPTION_ROLE, options, queryParams);
    migrateQueryParameter(WGDatabase.QUERYOPTION_MAXRESULTS, options, queryParams);
    migrateQueryParameter(WGDatabase.QUERYOPTION_EXCLUDEDOCUMENT, options, queryParams);
    migrateQueryParameter(WGDatabase.QUERYOPTION_ENHANCE, options, queryParams);
    migrateQueryParameter(WGDatabase.QUERYOPTION_ONLYRELEASED, options, queryParams);

    WGAbstractResultSet resultSet = _db.query("hql", hql.toString(), parameters);

    // Migrate output parameters back
    try {
        migrateQueryParameter(WGDatabase.QUERYOPTION_RETURNQUERY, parameters, options);
    } catch (UnsupportedOperationException e) {
        // Silently ignore if options map is unmodifiable
    }

    return resultSet;

}

From source file:org.commonjava.maven.galley.maven.model.view.MavenXmlView.java

/**
 * Select the first node matching the given XPath expression, rooted in the given context. If cachePath 
 * is true, compile the XPath expression and cache for future use. This is useful if the expression isn't
 * overly specific, and will be used multiple times.
 *//*  w w  w.j  a  v a2s.  c  om*/
protected synchronized Node resolveXPathToNodeFrom(final JXPathContext context, final String path,
        final boolean cachePath) {
    return (Node) context.selectSingleNode(path);
}

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

private static Object evaluateXpathExpression(Expression fireflowExpression,
        Map<String, Object> contextObjects) {
    Map<String, String> namespacePrefixUriMap = fireflowExpression.getNamespaceMap();

    JXPathContext jxpathContext = JXPathContext.newContext(contextObjects);
    jxpathContext.setFactory(w3cDomFactory);
    if (namespacePrefixUriMap != null) {
        Iterator<String> prefixIterator = namespacePrefixUriMap.keySet().iterator();
        while (prefixIterator.hasNext()) {
            String prefix = prefixIterator.next();
            String nsUri = namespacePrefixUriMap.get(prefix);
            jxpathContext.registerNamespace(prefix, nsUri);
        }// ww  w .j  av  a  2s . com
    }

    //W3C DOM
    //TODO ?dom4j document?jdom document
    Object obj = null;
    Object _node = jxpathContext.selectSingleNode(fireflowExpression.getBody());
    if (_node instanceof org.w3c.dom.Node) {
        if (_node instanceof org.w3c.dom.Document) {
            obj = _node;
        } else {
            obj = ((org.w3c.dom.Node) _node).getTextContent();
        }
    } else {
        obj = _node;
    }
    return obj;
}

From source file:org.freud.analysed.javasource.jdom.AnnotationJdom.java

private String getAnnotationValueForElement(final Element element) {
    final JXPathContext context = JXPathContext.newContext(element);
    final Element expr = (Element) context.selectSingleNode("/" + JavaSourceTokenType.EXPR.name() + "/*");
    if (expr != null) {
        return expr.getText();
    } else {/*from   ww w.j  a v  a2s  .c o m*/
        final List<Element> exprList = context.selectNodes("//" + JavaSourceTokenType.EXPR.name() + "/*");
        StringBuilder sb = new StringBuilder("{");
        for (Element item : exprList) {
            sb.append(item.getText()).append(",");
        }
        sb.setCharAt(sb.length() - 1, '}');
        return sb.toString();
    }
}

From source file:org.freud.analysed.javasource.jdom.ClassDeclarationJdom.java

public String getSuperClassName() {
    if (superClassName == NOT_RETRIEVED) {
        JXPathContext context = JXPathContext.newContext(classDeclElement);

        final Element superClassElement = (Element) context
                .selectSingleNode("/" + EXTENDS_CLAUSE.getName() + "//" + IDENT.getName());
        superClassName = (null == superClassElement) ? null : superClassElement.getValue();
    }/*from w  ww.  ja va  2 s .  co m*/
    return superClassName;
}

From source file:org.freud.analysed.javasource.jdom.JavaSourceJdom.java

private ClassDeclaration parseClassDeclaration() {

    JXPathContext context = JXPathContext.newContext(root);
    for (JavaSourceTokenType tokenType : POSSIBLE_CLASS_DECLARATION_TYPES) {
        try {//from w  w w .  j av a 2 s.  c o  m
            final String tokenName = tokenType.name();
            final Element element = (Element) context
                    .selectSingleNode("/" + JAVA_SOURCE_ROOT_ELEMENT_NAME + "/" + tokenName);
            if (element != null) {
                classDeclaration = new ClassDeclarationJdom(element, getDeclarationType(tokenType), null);
            }
        } catch (JXPathException e) {
            // ignore and try another path
        }
    }
    if (classDeclaration == null) {
        throw new IllegalStateException("Internal: could not find class declaration in: " + this);
    }

    return classDeclaration;
}

From source file:org.freud.analysed.javasource.jdom.JavaSourceJdom.java

private PackageDeclaration parsePackageDeclaration() {
    try {//ww w . ja  va2  s . c  o m
        JXPathContext context = JXPathContext.newContext(root);
        packageDeclaration = new PackageDeclarationJdom((Element) context.selectSingleNode(
                "/" + JAVA_SOURCE_ROOT_ELEMENT_NAME + "/" + JavaSourceTokenType.PACKAGE.name()));
    } catch (JXPathException e) {
        packageDeclaration = new PackageDeclarationJdom();
    }

    return packageDeclaration;
}

From source file:org.freud.analysed.javasource.jdom.MethodDeclarationJdom.java

public CodeBlock getImplementation() {
    if (methodCodeBlock == null) {
        try {/*  ww  w . jav a 2s . com*/
            JXPathContext context = JXPathContext.newContext(methodDeclElement);
            Element codeBlockElement = (Element) context
                    .selectSingleNode("/" + JavaSourceTokenType.BLOCK_SCOPE.getName());
            methodCodeBlock = CodeBlockJdom.createMethodImplementation(codeBlockElement, this,
                    classDeclaration);
        } catch (JXPathException e) {
            return null;
        }
    }
    return methodCodeBlock;
}