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

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

Introduction

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

Prototype

public static JXPathContext newContext(Object contextBean) 

Source Link

Document

Creates a new JXPathContext with the specified object as the root node.

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.tokit.TokenMerger.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    CAS cas = aJCas.getCas();/*from   www . j a  v  a  2s  .c  om*/

    if (posValue != null) {
        mappingProvider.configure(cas);
    }

    Collection<Annotation> toRemove = new ArrayList<Annotation>();
    for (AnnotationFS cover : CasUtil.select(cas, CasUtil.getAnnotationType(cas, annotationType))) {
        List<Token> covered = selectCovered(Token.class, cover);
        if (covered.size() < 2) {
            continue;
        }

        if (constraint != null) {
            JXPathContext ctx = JXPathContext.newContext(cover);
            boolean match = ctx.iterate(constraint).hasNext();
            if (!match) {
                continue;
            }
        }

        Iterator<Token> i = covered.iterator();

        // Extend first token
        Token token = i.next();
        token.setEnd(covered.get(covered.size() - 1).getEnd());

        // Optionally update the POS value
        if (posValue != null) {
            updatePos(token, toRemove);
        }

        // Record lemma - may be needed for join later
        List<String> lemmata = new ArrayList<String>();
        if (token.getLemma() != null) {
            lemmata.add(token.getLemma().getValue());
        }

        // Mark the rest for deletion - record lemmata if desired for later join
        while (i.hasNext()) {
            Token t = i.next();

            Lemma lemma = t.getLemma();
            if (lemma != null) {
                lemmata.add(lemma.getValue());
                toRemove.add(lemma);
            }

            POS pos = t.getPos();
            if (pos != null) {
                toRemove.add(pos);
            }

            toRemove.add(t);
        }

        // Join lemmata if desired
        if (lemmaMode == LemmaMode.JOIN) {
            Lemma lemma = token.getLemma();
            if (!lemmata.isEmpty()) {
                if (lemma == null) {
                    lemma = new Lemma(aJCas);
                }
                lemma.setValue(StringUtils.join(lemmata, " "));
            }
            // Remove if there was nothing to join... I don't really ever expect to get here
            else if (lemma != null) {
                token.setLemma(null);
                toRemove.add(lemma);
            }
        }
        // Remove the lemma - if desired
        else if (lemmaMode == LemmaMode.REMOVE) {
            Lemma lemma = token.getLemma();
            if (lemma != null) {
                token.setLemma(null);
                toRemove.add(lemma);
            }
        }

        // Update offsets for lemma
        if (token.getLemma() != null) {
            token.getLemma().setBegin(token.getBegin());
            token.getLemma().setEnd(token.getEnd());
        }
    }

    // Remove tokens no longer needed
    for (Annotation t : toRemove) {
        t.removeFromIndexes();
    }
}

From source file:com.idega.util.config.DefaultConfig.java

/**
 * Creates and loads a new configuration.
 * /*from w ww.j a v a  2s.c  o m*/
 * @param stream
 *            InputStream to read XML data in the default format.
 */
public DefaultConfig(InputStream stream) throws ConfigException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);

        Document document = factory.newDocumentBuilder().parse(stream);
        JXPathContext context = JXPathContext.newContext(document.getDocumentElement());

        for (Iterator iter = context.iteratePointers(properties_xpath); iter.hasNext();) {
            Pointer pointer = (Pointer) iter.next();
            Element properties_el = (Element) pointer.getNode();
            String p_name = properties_el.getAttribute(name_att);

            JXPathContext properties_context = JXPathContext.newContext(properties_el);
            Map<String, String> properties = load(properties_context, property_xpath, name_att, value_att);
            getPropertiesMap().put(p_name, properties);
        }

    } catch (Exception e) {
        throw new ConfigException(e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.tokit.TokenMergerTest.java

@SuppressWarnings("unchecked")
public static List<Object> pick(Collection<?> aContext, String aPath) {
    List<Object> result = new ArrayList<Object>();
    for (Object a : aContext) {
        JXPathContext ctx = JXPathContext.newContext(a);
        ctx.setFunctions(new ClassFunctions(JXPathCasFunctions.class, "cas"));
        result.addAll(ctx.selectNodes(aPath));
    }/*from w  w  w  .  ja v a  2s .  c o m*/
    return result;
}

From source file:net.sbbi.upnp.devices.UPNPRootDevice.java

/**
 * Constructor for the root device, constructs itself from
 * An xml device definition file provided by the UPNP device via http normally.
 * @param deviceDefLoc the location of the XML device definition file
 *                     using "the urn:schemas-upnp-org:device-1-0" namespace
 * @param maxAge the maximum age in secs of this UPNP device before considered to be outdated
 * @throws MalformedURLException if the location URL is invalid and cannot be used to populate this root object and its child devices
 *         IllegalStateException if the device has an unsupported version, currently only version 1.0 is supported
 *///  w  w  w.j  a  v  a  2 s  . c  o  m
public UPNPRootDevice(URL deviceDefLoc, String maxAge) throws MalformedURLException, IllegalStateException {
    this.deviceDefLoc = deviceDefLoc;
    DocumentContainer.registerXMLParser(DocumentContainer.MODEL_DOM, new JXPathParser());
    UPNPDevice = new DocumentContainer(deviceDefLoc, DocumentContainer.MODEL_DOM);
    validityTime = Integer.parseInt(maxAge) * 1000;
    creationTime = System.currentTimeMillis();

    JXPathContext context = JXPathContext.newContext(this);
    Pointer rootPtr = context.getPointer("UPNPDevice/root");
    JXPathContext rootCtx = context.getRelativeContext(rootPtr);

    specVersionMajor = Integer.parseInt((String) rootCtx.getValue("specVersion/major"));
    specVersionMinor = Integer.parseInt((String) rootCtx.getValue("specVersion/minor"));

    if (!(specVersionMajor == 1 && specVersionMinor == 0)) {
        throw new IllegalStateException(
                "Unsupported device version (" + specVersionMajor + "." + specVersionMinor + ")");
    }
    boolean buildURLBase = true;
    String base = null;
    try {
        base = (String) rootCtx.getValue("URLBase");
        if (base != null && base.trim().length() > 0) {
            URLBase = new URL(base);
            if (log.isDebugEnabled())
                log.debug("device URLBase " + URLBase);
            buildURLBase = false;
        }
    } catch (JXPathException ex) {
        // URLBase is not mandatory we assume we use the URL of the device
    } catch (MalformedURLException malformedEx) {
        // crappy urlbase provided
        log.warn("Error occured during device baseURL " + base
                + " parsing, building it from device default location", malformedEx);
    }
    if (buildURLBase) {
        String URL = deviceDefLoc.getProtocol() + "://" + deviceDefLoc.getHost() + ":" + deviceDefLoc.getPort();
        String path = deviceDefLoc.getPath();
        if (path != null) {
            int lastSlash = path.lastIndexOf('/');
            if (lastSlash != -1) {
                URL += path.substring(0, lastSlash);
            }
        }
        URLBase = new URL(URL);
    }
    Pointer devicePtr = rootCtx.getPointer("device");
    JXPathContext deviceCtx = rootCtx.getRelativeContext(devicePtr);

    fillUPNPDevice(this, null, deviceCtx, URLBase);
}

From source file:de.innovationgate.wgpublisher.webtml.Item.java

public void tmlEndTag() throws WGException, TMLException {

    String itemName = this.getName();
    TMLContext tmlContext = this.getTMLContext();
    List result = null;//from w w  w  . ja  v  a2 s. c  o  m
    String type = this.getType();

    // add warning on illegal use of highlight attribute
    if (stringToBoolean(getHighlight())) {
        if (!type.equals("content")) {
            addWarning("Highlighting can only be used with type 'content' - skipped.");
        }
    }

    // Retrieve value
    if (type.equals("content")) {
        result = tmlContext.itemlist(itemName, buildNamedActionParameters(false));
        if (stringToBoolean(getHighlight())) {
            if (this.stringToBoolean(this.getScriptlets())) {
                addWarning("Highlighting cannot be used with scriptlets - skipped.");
            } else if (this.getAliases() != null) {
                addWarning("Highlighting cannot be used with aliases - skipped.");
            } else if (getXpath() != null) {
                addWarning("Highlighting cannot be used together with xpath - skipped.");
            } else {
                // highlight itemvalue with information from lucene query
                result = Collections.singletonList(tmlContext.highlightitem(itemName, getHighlightprefix(),
                        getHighlightsuffix(), getStatus().encode));
                getStatus().encode = "none";
            }
        }
    } else if (type.equals("profile")) {
        TMLUserProfile profile = tmlContext.getprofile();
        if (profile == null) {
            this.addWarning("Current user has no profile", true);
            return;
        }
        result = profile.itemlist(itemName);
    } else if (type.equals("portlet")) {
        TMLPortlet portlet = tmlContext.getportlet();
        if (portlet == null) {
            this.addWarning("Current user has no portlet registration", true);
            return;
        }
        result = portlet.itemlist(itemName);
    } else if (type.equals("tmlform")) {
        TMLForm form = tmlContext.gettmlform();
        if (form == null) {
            addWarning("There is no current WebTML form at this position in the current request");
            return;
        }
        result = form.fieldlist(itemName);
    }

    // The item does not exist or is empty. Treat as empty list.
    if (result == null) {
        result = new ArrayList();
    }

    // Eventually execute xpath
    String xpath = getXpath();
    if (xpath != null && result.size() > 0) {
        Object firstResult = result.get(0);
        if (firstResult instanceof Node) {
            Node resultNode = (Node) firstResult;
            result = resultNode.selectNodes(xpath);
        } else if (firstResult instanceof String) {
            try {
                Document doc = DocumentHelper.parseText((String) firstResult);
                result = doc.selectNodes(xpath);
            } catch (DocumentException e) {
                addWarning("Unable to parse item content '" + itemName + "' as XML: " + firstResult);
            }
        } else if (ExpressionEngineFactory.getTMLScriptEngine()
                .determineTMLScriptType(firstResult) == RhinoExpressionEngine.TYPE_XMLOBJECT) {
            result = ExpressionEngineFactory.getTMLScriptEngine().xpathTMLScriptBean(firstResult, xpath);
        } else {
            JXPathContext jxcontext = JXPathContext.newContext(firstResult);
            Iterator jxresults = jxcontext.iterate(xpath);
            result = new ArrayList();
            while (jxresults.hasNext()) {
                result.add(jxresults.next());
            }
        }
    }

    // Eventually resolve scriptlets
    if (result.size() > 0 && this.stringToBoolean(this.getScriptlets()) == true) {
        RhinoExpressionEngine engine = ExpressionEngineFactory.getTMLScriptEngine();
        String resolvedResultStr = null;
        try {
            Map params = new HashMap();
            params.put(RhinoExpressionEngine.SCRIPTLETOPTION_LEVEL, RhinoExpressionEngine.LEVEL_SCRIPTLETS);
            resolvedResultStr = engine.resolveScriptlets(result.get(0), getTMLContext(), params);
            result = new ArrayList();
            result.add(resolvedResultStr);
        } catch (Exception e) {
            throw new TMLException("Exception parsing scriptlets", e, false);
        }
    }

    // BI-Editor (See Root-Class for attrib WGACore.ATTRIB_EDITDOCUMENT)
    Object attribEdit = this.getPageContext().getRequest().getAttribute(WGACore.ATTRIB_EDITDOCUMENT);
    if (attribEdit != null && getEditor() != null
            && attribEdit.equals(this.getTMLContext().getcontent().getContentKey().toString())) {
        buildEditor(itemName, result);
        setResult(result);
    } else {
        // if aliases are defined, replace values with aliases
        List aliases = this.retrieveAliases();
        if (aliases.isEmpty())
            this.setResult(result);
        else {
            WGA wga = WGA.get();
            this.setResult(wga.aliases(WGUtils.toString(result), aliases));
        }

    }
}

From source file:com.ebay.jetstream.epl.EPLUtilities.java

public static Object getAttribute(Object object, String key) {
    try {/*from w  w w.ja  va 2s  . com*/
        Object event = object;
        if (object instanceof String) {
            ObjectMapper mapper = new ObjectMapper();
            event = mapper.readValue(object.toString(), HashMap.class);
        }
        if (event != null) {
            JXPathContext context = JXPathContext.newContext(event);
            context.setLenient(true);
            return context.getValue(key);
        }
    } catch (Exception e) { // NOPMD
        return null;
    }
    return null;
}

From source file:jsondb.JsonDBTemplate.java

public void reloadCollection(String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    cmd.getCollectionLock().writeLock().lock();
    try {/*from  ww  w.j  ava2  s  .  c  o  m*/
        File collectionFile = fileObjectsRef.get().get(collectionName);
        if (null == collectionFile) {
            // Lets create a file now
            collectionFile = new File(dbConfig.getDbFilesLocation(),
                    dbConfig.getDBPrefix() + collectionName + ".json");
            if (!collectionFile.exists()) {
                throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName
                        + "' cannot be found at " + collectionFile.getAbsolutePath());
            }
            Map<String, File> fileObjectMap = fileObjectsRef.get();
            Map<String, File> newFileObjectmap = new ConcurrentHashMap<String, File>(fileObjectMap);
            newFileObjectmap.put(collectionName, collectionFile);
            fileObjectsRef.set(newFileObjectmap);
        }
        if (null != cmd && null != collectionFile) {
            Map<Object, ?> collection = loadCollection(collectionFile, collectionName, cmd);
            if (null != collection) {
                JXPathContext newContext = JXPathContext.newContext(collection.values());
                contextsRef.get().put(collectionName, newContext);
                collectionsRef.get().put(collectionName, collection);
            } else {
                //Since this is a reload attempt its possible the .json files have disappeared in the interim a very rare thing
                contextsRef.get().remove(collectionName);
                collectionsRef.get().remove(collectionName);
            }
        }
    } finally {
        cmd.getCollectionLock().writeLock().unlock();
    }
}

From source file:de.innovationgate.wga.server.api.Xml.java

/**
 * Executes an XPath expression on some XML text or JavaBean
 * This function always returns lists. If the xpath expression matches only a single values it will return it as single element in a list. If you only want to retrieve single values use xpath().
 * The given object to parse as XML is either a dom4j branch object (mostly document or element), a String containing XML text or a JavaBean. In the last case this function uses JXPath functionality to find a bean property value.
 * This uses the Apache library JXPath under the hood. See their documentation for details how XPath is used to browser JavaBeans.
 * @param object Object to inspect//ww  w . ja  va2  s . c  o m
 * @param xpath XPath expression
 * @param ns Map of namespace prefix declarations used in the XPath. Keys are prefixes, values are namespace URIs.
 * @return Returned value
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
public Object xpathList(Object object, String xpath, Map<String, String> ns)
        throws WGException, DocumentException {
    List<Object> results;
    if (object instanceof String || object instanceof Branch) {
        Branch branch = retrieveBranch(object);
        XPath xpathObj = createXPath(xpath, branch, ns);
        results = xpathObj.selectNodes(branch);
    }

    // Do JXPath on Bean
    else {
        JXPathContext jxContext = JXPathContext.newContext(object);
        jxContext.setLenient(true);
        results = jxContext.selectNodes(xpath);
    }
    return convertXMLObjects(results, true);
}

From source file:io.jsondb.JsonDBTemplate.java

public void reloadCollection(String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    cmd.getCollectionLock().writeLock().lock();
    try {//from  ww  w.  jav  a2s  . c o  m
        File collectionFile = fileObjectsRef.get().get(collectionName);
        if (null == collectionFile) {
            // Lets create a file now
            collectionFile = new File(dbConfig.getDbFilesLocation(), collectionName + ".json");
            if (!collectionFile.exists()) {
                throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName
                        + "' cannot be found at " + collectionFile.getAbsolutePath());
            }
            Map<String, File> fileObjectMap = fileObjectsRef.get();
            Map<String, File> newFileObjectmap = new ConcurrentHashMap<String, File>(fileObjectMap);
            newFileObjectmap.put(collectionName, collectionFile);
            fileObjectsRef.set(newFileObjectmap);
        }
        if (null != cmd && null != collectionFile) {
            Map<Object, ?> collection = loadCollection(collectionFile, collectionName, cmd);
            if (null != collection) {
                JXPathContext newContext = JXPathContext.newContext(collection.values());
                contextsRef.get().put(collectionName, newContext);
                collectionsRef.get().put(collectionName, collection);
            } else {
                //Since this is a reload attempt its possible the .json files have disappeared in the interim a very rare thing
                contextsRef.get().remove(collectionName);
                collectionsRef.get().remove(collectionName);
            }
        }
    } finally {
        cmd.getCollectionLock().writeLock().unlock();
    }
}

From source file:com.axelor.data.xml.XMLBinder.java

@SuppressWarnings("unchecked")
private List<Node> find(Node node, XMLBind bind, String prefix) {
    List<Node> nodes = Lists.newArrayList();
    String name = bind.getNode();
    String path = name;/*  w w  w. j  a v  a 2  s. c  o  m*/

    if (name == null) {
        return nodes;
    }

    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    if (!("/".equals(prefix))) {
        path = prefix + path;
    }

    try {
        LOG.trace("xpath: " + path);
        JXPathContext context = JXPathContext.newContext(node);
        nodes = context.selectNodes(path);
        LOG.trace("xpath match: " + nodes.size());
    } catch (Exception e) {
        LOG.error("Invalid xpath expression: {}", path);
    }
    return nodes;
}