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:com.abien.patterns.business.lazy.JXPathTest.java

@Test
public void lazyLoadOneToOneToOne() {
    Object value = JXPathContext.newContext(master).getValue("/detail/subDetail");
    assertNotNull(value);// w  w  w.ja v a  2 s  .co  m
    assertTrue(value instanceof SubDetail);
}

From source file:com.ixcode.framework.model.binding.ModelXPathResolver.java

/**
 * @todo maybe there is already a way to deal witht he root domain being a collection ?
 * @todo this is a nasteee way of doing it - we need to work out how to sort it...
 * /[10]/someCollection[1]// www .j  av a2  s .c  o  m
 * @param xpath
 * @return
 */
public Object getModel(String xpath) {
    Object model;
    if (xpath.length() == 0) {
        model = _pathContext.getValue("/");
    } else if (xpath.startsWith("/[")) { // must be a collection in the root ...
        int index = Integer.parseInt(xpath.substring(2, xpath.indexOf(']')));
        Collection rootCollection = (Collection) _pathContext.getValue("/");
        model = findModel(rootCollection, index);
        String childPath = xpath.substring(xpath.indexOf(']') + 1);
        if (childPath.startsWith("/")) {
            JXPathContext childContext = JXPathContext.newContext(model);
            model = childContext.getValue(childPath);
        }
    } else {
        model = _pathContext.getValue(xpath);
    }
    return model;
}

From source file:com.pavelvlasov.uml.eval.JXPathEvaluator.java

public String evaluate(String expr, Object contextObject) {
    Object res = null;//from  w  w w . j  a  v  a2 s .  co m
    if (contextObject instanceof Element) {
        res = ((Element) contextObject).navigate(expr);
    } else {
        JXPathContext parentContext = parentContextResolver == null ? null
                : parentContextResolver.resolveParentContext(contextObject);

        /*
         * Don't cache results if parent context resolver is not null
         */
        if (parentContextResolver != null) {
            CachingInvocationHandler.doNotCacheCurrentResult();
        }

        JXPathContext context = parentContext == null ? JXPathContext.newContext(contextObject)
                : JXPathContext.newContext(parentContext, contextObject);
        res = context.getValue(expr);
    }
    return res == null ? "" : res.toString();
}

From source file:com.discursive.jccook.xml.jxpath.TeamExample.java

public void start() throws Exception {
    League league = new League();

    Team team = new Team();
    league.getTeams().add(team);//ww  w  .ja  v a2s .  c  o  m

    Person coach = new Person();
    coach.setFirstName("Coach Bob");
    team.setCoach(coach);

    Person player1 = new Person();
    player1.setFirstName("Player Charlie");
    team.getPlayers().add(player1);

    Person player2 = new Person();
    player2.setFirstName("Player Ted");
    team.getPlayers().add(player2);

    Person player3 = new Person();
    player3.setFirstName("Player Bart");
    team.getPlayers().add(player3);

    Team team2 = new Team();
    league.getTeams().add(team2);

    Person coach2 = new Person();
    coach2.setFirstName("Coach Susan");
    team2.setCoach(coach2);

    Person player4 = new Person();
    player4.setFirstName("Player Jim");
    team2.getPlayers().add(player4);

    JXPathContext context = JXPathContext.newContext(league);
    System.out.println("** Retrieve the first name of Ted's coach");
    Object value = context.getValue("teams/players[firstName = 'Player Ted']/../coach/firstName");
    System.out.println(value);

    context = JXPathContext.newContext(league);
    System.out.println("** Retrieve the players on Coach Susan's team");
    value = context.getValue("teams/coach[firstName = 'Coach Susan']/../players");
    System.out.println(value);
}

From source file:com.discursive.jccook.xml.jxpath.PersonExample.java

public void start() throws IOException, SAXException {

    List people = new ArrayList();

    Person person1 = new Person();
    person1.setFirstName("Ahmad");
    person1.setLastName("Russell");
    person1.setAge(28);//from  ww  w  .j a va 2s .  c  o m
    people.add(person1);

    Person person2 = new Person();
    person2.setFirstName("Tom");
    person2.setLastName("Russell");
    person2.setAge(35);
    people.add(person2);

    Person person3 = new Person();
    person3.setFirstName("Ahmad");
    person3.setLastName("Abuzayedeh");
    person3.setAge(33);
    people.add(person3);

    System.out.println("** People older than 30");
    JXPathContext context = JXPathContext.newContext(people);
    Iterator iterator = context.iterate(".[@age > 30]");
    printPeople(iterator);

    context = JXPathContext.newContext(people);
    System.out.println("** People with first name 'Ahmad'");
    iterator = context.iterate(".[@firstName = 'Ahmad']");
    printPeople(iterator);

    context = JXPathContext.newContext(people);
    System.out.println("** Second Person in List");
    Person p = (Person) context.getValue(".[2]");
    System.out.println("Person: " + p.getFirstName() + " " + p.getLastName() + ", age: " + p.getAge());
}

From source file:com.discursive.jccook.xml.jxpath.PlanetSearch.java

public void planetSearch() throws IOException, SAXException {
    List planets = new ArrayList();

    InputStream input = getClass().getResourceAsStream("./planets.xml");
    URL rules = getClass().getResource("./planet-digester-rules.xml");
    Digester digester = DigesterLoader.createDigester(rules);
    digester.push(planets);/*from  w w  w  .  j av a  2s. com*/
    digester.parse(input);

    System.out.println("Number of planets: " + planets.size());

    System.out.println("Planet Name where radius > 5000");
    JXPathContext context = JXPathContext.newContext(planets);
    Iterator iterator = context.iterate(".[@radius > 5000]/name");
    while (iterator.hasNext()) {
        Object o = (Object) iterator.next();
        System.out.println("Object: " + o);
    }

    System.out.println("Planet Name where a moon is named Deimos");
    iterator = context.iterate("./moons[. = 'Deimos']/../name");
    while (iterator.hasNext()) {
        String name = (String) iterator.next();
        System.out.println("Planet Namet: " + name);
    }

    System.out.println("Planet where Helium percentage greater than 2");
    iterator = context.iterate("./atmosphere/components/He[.>2]/../../..");
    while (iterator.hasNext()) {
        Planet p = (Planet) iterator.next();
        System.out.println("Planet: " + p.getName());
    }

    System.out.println("All of the Moon Names");
    iterator = context.iterate("./moons");
    while (iterator.hasNext()) {
        String moon = (String) iterator.next();
        context.getVariables().declareVariable("moonName", moon);
        String planet = (String) context.getValue("./moons[. = $moonName]/../name");
        System.out.println("Moon: " + moon + ", \t\t\tPlanet: " + planet);
    }
}

From source file:com.intuit.tank.http.json.JsonResponse.java

@Override
public String getValue(String key) {

    try {/*  w  ww.  j  a v a 2  s .  co  m*/
        if (NumberUtils.isDigits(key)) {
            Integer.parseInt(key);
            JSONObject jsonResponse = new JSONObject(this.response);
            return (String) jsonResponse.get(key);
        }
    } catch (Exception e) {
    }
    try {
        if (this.jsonMap == null) {
            initialize();
        }
        String keyTrans = key.replace("@", "");
        // note that indexing is 1 based not zero based
        JXPathContext context = JXPathContext.newContext(this.jsonMap);
        String output = URLDecoder.decode(String.valueOf(context.getValue(keyTrans)), "UTF-8");
        if (output.equalsIgnoreCase("null"))
            return "";
        return output;
    } catch (Exception ex) {
        return "";
    }
}

From source file:com.technofovea.hl2parse.vdf.MaterialReader.java

public MaterialReader(VdfRoot rootNode, MaterialRefList props) {
    root = rootNode;//from w  ww .  j  av  a 2 s.  c o  m
    context = JXPathContext.newContext(root);
    JxPathUtil.addFunctions(context);

    Iterator<VdfAttribute> allAttribs = context.iterate("//attributes");

    while (allAttribs.hasNext()) {
        VdfAttribute attrPair = allAttribs.next();
        String key = attrPair.getName();
        // Strip trailing "2"s for blend texture variations
        if (key.endsWith("2")) {
            logger.trace("Found 2-suffixed attribute variation: {}", key);
            key = key.substring(0, key.length() - 1);
        }

        if (key.equalsIgnoreCase(PATCH_INCLUDE)) {
            // According to docs, the patch shader's "include" directive
            // required a complete path with extension, ex.
            // materials/foo/bar.vmt
            // So we don't prefix or suffix this one
            logger.trace("Found possible patch-include shader material: {}", key);

            materials.add(attrPair.getValue());
        }

        for (MaterialReference ref : props) {
            if (!ref.hasName(key)) { // Case insensitive
                continue;
            }
            String val = attrPair.getValue();
            if (ref.hasIgnoreValue(val)) { // Case sensitive
                continue;
            }

            switch (ref.getType()) {
            case MATERIAL:
                logger.trace("Found material: {}", val);
                if (!val.toLowerCase().endsWith(".vmt")) {
                    val += ".vmt";
                }
                materials.add("materials/" + val);
                break;
            case TEXTURE:
                logger.trace("Found texture: {}", val);
                if (!val.toLowerCase().endsWith(".vtf")) {
                    val += ".vtf";
                }
                textures.add("materials/" + val);
                break;
            }
            break; // Break loop
        }
    }
}

From source file:blueprint.sdk.util.JXPathHelper.java

/**
 * @param xpath XPath to evaluate/*from   w  w w .j  a v a  2  s .c om*/
 * @param target target node
 * @return Iterator or null(not found)
 */
public static Iterator<String> evaluateIterator(String xpath, Node target) {
    return evaluateIterator(xpath, JXPathContext.newContext(target));
}

From source file:com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI.java

@SuppressWarnings("unchecked")
public List<Node> selectList(Node contextNode, String xpath) {
    @SuppressWarnings("rawtypes")
    List nodes;/*www. j a v  a  2 s . c o m*/
    try {
        nodes = JXPathContext.newContext(contextNode).selectNodes(xpath);
        int i = 0;
        for (Object node : nodes) {
            if (node instanceof String) {
                node = contextNode.getOwnerDocument().createTextNode((String) node);
                nodes.set(i, node);
            }
            i++;
        }
    } catch (Exception e) {
        nodes = Collections.emptyList();
    }
    return (List<Node>) nodes;
}