Beispiel #1
0
  public Object getProperty(String name, Object message) {

    Object result = null;
    Object payload = message;
    if (message instanceof UMOMessage) {
      payload = ((UMOMessage) message).getPayload();
    }

    if (payload instanceof String) {
      Document doc;
      try {
        doc = DocumentHelper.parseText((String) payload);
      } catch (DocumentException e) {
        logger.error(e);
        return null;
      }
      result = doc.valueOf(name);
    } else {
      JXPathContext context = JXPathContext.newContext(payload);
      try {
        result = context.getValue(name);
      } catch (Exception e) {
        // ignore
      }
    }
    return result;
  }
Beispiel #2
0
  /**
   * Initializes the JXPathContext based on any relevant properties set for the filter.
   *
   * @param context the JXPathContext to initialize
   */
  protected void initialise(JXPathContext context) {
    Map.Entry entry;
    if (namespaces != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Initializing JXPathContext with namespaces: " + namespaces);
      }

      for (Iterator iterator = namespaces.entrySet().iterator(); iterator.hasNext(); ) {
        entry = (Map.Entry) iterator.next();
        context.registerNamespace(entry.getKey().toString(), entry.getValue().toString());
      }
    }

    if (contextProperties != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Initializing JXPathContext with properties: " + contextProperties);
      }

      for (Iterator iterator = contextProperties.entrySet().iterator(); iterator.hasNext(); ) {
        entry = (Map.Entry) iterator.next();
        context.setValue(entry.getKey().toString(), entry.getValue());
      }
    }

    if (factory != null) {
      context.setFactory(factory);
    }

    context.setLenient(lenient);
  }
 public void testComplexOperationWithVariables() {
   JXPathContext context = JXPathContext.newContext(null);
   context.getVariables().declareVariable("a", Integer.valueOf(0));
   context.getVariables().declareVariable("b", Integer.valueOf(0));
   context.getVariables().declareVariable("c", Integer.valueOf(1));
   assertXPathValue(context, "$a + $b <= $c", Boolean.TRUE);
 }
Beispiel #4
0
  /**
   * Create a new context for the specified object that has access to the supplied functions.
   *
   * @param object the context bean
   * @param functions the functions
   * @return JXPathContext the context object
   */
  public static JXPathContext newContext(Object object, Functions functions) {
    JXPathContext context = JXPathContext.newContext(object);
    FunctionLibrary lib = new FunctionLibrary();
    lib.addFunctions(context.getFunctions());
    lib.addFunctions(functions);
    context.setFunctions(lib);
    context.setLenient(true);

    return context;
  }
Beispiel #5
0
 /**
  * Recupera un nodo del arbol a partir del path de dicho nodo dentro de la jerarquia
  *
  * @param nodePath
  * @return El nodo correspondiente al path solicitado o nulo en caso de no ser un paz valido
  *     dentro de la jerarquia
  */
 public TreeNode getNode(String nodePath) {
   synchronized (this) {
     try {
       JXPathIntrospector.registerDynamicClass(TreeNode.class, TreeNodeXPathHandler.class);
       JXPathIntrospector.registerDynamicClass(TreeView.class, TreeNodeXPathHandler.class);
       JXPathContext xPathContext = JXPathContext.newContext(this);
       return (TreeNode) xPathContext.getValue(nodePath);
     } catch (Exception e) {
       return null;
     }
   }
 }
Beispiel #6
0
  @SuppressWarnings("unchecked")
  public static synchronized Dir getDir(Dir dir, String code)
      throws ExlpXpathNotFoundException, ExlpXpathNotUniqueException {
    JXPathContext context = JXPathContext.newContext(dir);

    List<Dir> list = (List<Dir>) context.selectNodes("dir[@code='" + code + "']");
    if (list.size() == 0) {
      throw new ExlpXpathNotFoundException("No " + Dir.class.getSimpleName() + " for code=" + code);
    } else if (list.size() > 1) {
      throw new ExlpXpathNotUniqueException(
          "Multiple " + Dir.class.getSimpleName() + "s for code=" + code);
    }
    return list.get(0);
  }
  public Object evaluate(NodeDefinition context, NodeDefinition thisNode) {
    if (!(Schema.class.isAssignableFrom(context.getClass())
        || NodeDefinition.class.isAssignableFrom(context.getClass()))) {
      throw new IllegalArgumentException(
          "Unable to evaluate expression with context class " + context.getClass().getName());
    }
    JXPathContext jxPathContext = JXPathContext.newContext(CONTEXT, context);
    Variables variables = jxPathContext.getVariables();
    variables.declareVariable(AbstractExpression.THIS_VARIABLE_NAME, thisNode);

    String expr = Path.getNormalizedPath(expression);
    Object result = jxPathContext.getValue(expr);
    return result;
  }
  /** Tests simple XPath expressions. */
  public void testSimpleXPath() {
    List nodes = context.selectNodes(CHILD_NAME1);
    assertEquals("Incorrect number of results", 2, nodes.size());
    for (Iterator it = nodes.iterator(); it.hasNext(); ) {
      ConfigurationNode node = (ConfigurationNode) it.next();
      assertEquals("Incorrect node name", CHILD_NAME1, node.getName());
      assertEquals("Incorrect parent node", root, node.getParentNode());
    }

    nodes = context.selectNodes("/" + CHILD_NAME1);
    assertEquals("Incorrect number of results", 2, nodes.size());

    nodes = context.selectNodes(CHILD_NAME2 + "/" + CHILD_NAME1 + "/" + CHILD_NAME2);
    assertEquals("Incorrect number of results", 18, nodes.size());
  }
Beispiel #9
0
 /** 根据给定的xpath查询Page对象 */
 private Page searchPageWithXpath(Object o, String... xpaths) {
   JXPathContext context = JXPathContext.newContext(o);
   Object result;
   for (String xpath : xpaths) {
     try {
       result = context.selectSingleNode(xpath);
     } catch (Exception e) {
       continue;
     }
     if (result instanceof Page) {
       return (Page) result;
     }
   }
   return null;
 }
 /** Tests accessing the following sibling axis. */
 public void testFollowingSiblingAxis() {
   List nodes = context.selectNodes("/" + CHILD_NAME1 + "[2]/following-sibling::*");
   assertEquals("Wrong number of following siblings", 1, nodes.size());
   ConfigurationNode node = (ConfigurationNode) nodes.get(0);
   assertEquals("Wrong node type", CHILD_NAME2, node.getName());
   assertEquals("Wrong index", String.valueOf(CHILD_COUNT), node.getValue());
 }
  /**
   * Actively performs the binding from the ObjectModel wrapped in a jxpath context to the
   * CForms-form-widget specified in this object.
   */
  public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Widget widget = selectWidget(frmModel, this.fieldId);
    if (widget == null) {
      throw new BindingException(
          "The widget with the ID ["
              + this.fieldId
              + "] referenced in the binding does not exist in the form definition.");
    }

    Object value = jxpc.getValue(this.xpath);
    if (value != null && convertor != null) {
      if (value instanceof String) {
        ConversionResult conversionResult =
            convertor.convertFromString((String) value, convertorLocale, null);
        if (conversionResult.isSuccessful()) value = conversionResult.getResult();
        else value = null;
      } else {
        getLogger().warn("Convertor ignored on backend-value which isn't of type String.");
      }
    }

    widget.setValue(value);
    if (getLogger().isDebugEnabled()) {
      getLogger().debug("Done loading " + this + " -- value= " + value);
    }
  }
  /** Tests the {@link ListFunctions#sortNamesOf(ExpressionContext, String)} method */
  @Test
  public void testSortNamesOf() {
    Party vet = (Party) create(SupplierArchetypes.SUPPLIER_VET);
    vet.addClassification(createVetSpecialty("Surgery"));
    vet.addClassification(createVetSpecialty("Large Animals"));
    vet.addClassification(createVetSpecialty("Snakes"));

    JXPathContext ctx = createContext(vet);

    assertEquals(
        "Large Animals, Snakes, Surgery", ctx.getValue("list:sortNamesOf('classifications')"));

    assertEquals(
        "(Large Animals, Snakes, Surgery)",
        ctx.getValue("expr:concatIf('(', list:sortNamesOf('classifications'), ')')"));
  }
  static {
    JXPathIntrospector.registerDynamicClass(
        NodeDefinition.class, NodeDefinitionPropertyHandler.class);
    JXPathIntrospector.registerDynamicClass(Schema.class, SchemaPropertyHandler.class);

    CONTEXT = JXPathContext.newContext(null);
  }
Beispiel #14
0
  public static synchronized Listing getSeed(Section section, String id)
      throws ExlpXpathNotFoundException, ExlpXpathNotUniqueException {
    JXPathContext context = JXPathContext.newContext(section);

    StringBuffer sb = new StringBuffer();
    sb.append("//*[@id='" + id + "']");

    @SuppressWarnings("unchecked")
    List<Listing> listResult = (List<Listing>) context.selectNodes(sb.toString());
    if (listResult.size() == 0) {
      throw new ExlpXpathNotFoundException("No " + Listing.class.getSimpleName() + " for id=" + id);
    } else if (listResult.size() > 1) {
      throw new ExlpXpathNotUniqueException(
          "Multiple " + Listing.class.getSimpleName() + " for id=" + id);
    }
    return listResult.get(0);
  }
  /** Tests accessing attributes. */
  public void testAttributes() {
    root.addAttribute(new DefaultConfigurationNode("testAttr", "true"));
    assertEquals("Did not find attribute of root node", "true", context.getValue("@testAttr"));
    assertEquals(
        "Incorrect attribute value",
        "1",
        context.getValue("/" + CHILD_NAME2 + "[1]/@" + ATTR_NAME));

    assertTrue(
        "Found elements with name attribute",
        context.selectNodes("//" + CHILD_NAME2 + "[@name]").isEmpty());
    ConfigurationNode node =
        (ConfigurationNode) root.getChild(2).getChild(1).getChildren(CHILD_NAME2).get(1);
    node.addAttribute(new DefaultConfigurationNode("name", "testValue"));
    List nodes = context.selectNodes("//" + CHILD_NAME2 + "[@name]");
    assertEquals("Name attribute not found", 1, nodes.size());
    assertEquals("Wrong node returned", node, nodes.get(0));
  }
  /** Tests using indices to specify elements. */
  public void testIndices() {
    assertEquals(
        "Incorrect value",
        "1.2.3",
        context.getValue("/" + CHILD_NAME2 + "[1]/" + CHILD_NAME1 + "[1]/" + CHILD_NAME2 + "[2]"));
    assertEquals(
        "Incorrect value of last node",
        String.valueOf(CHILD_COUNT),
        context.getValue(CHILD_NAME2 + "[last()]"));

    List nodes = context.selectNodes("/" + CHILD_NAME1 + "[1]/*");
    assertEquals("Wrong number of children", CHILD_COUNT, nodes.size());
    int index = 1;
    for (Iterator it = nodes.iterator(); it.hasNext(); index++) {
      ConfigurationNode node = (ConfigurationNode) it.next();
      assertEquals("Wrong node value for child " + index, "2." + index, node.getValue());
    }
  }
 /** Tests accessing the preceding sibling axis. */
 public void testPrecedingSiblingAxis() {
   List nodes = context.selectNodes("/" + CHILD_NAME1 + "[2]/preceding-sibling::*");
   assertEquals("Wrong number of preceding siblings", 3, nodes.size());
   for (int index = 0, value = 3; index < nodes.size(); index++, value--) {
     assertEquals(
         "Wrong node index",
         String.valueOf(value),
         ((ConfigurationNode) nodes.get(index)).getValue());
   }
 }
  /**
   * Actively performs the binding from the CForms-form to the ObjectModel wrapped in a jxpath
   * context
   */
  public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Widget widget = selectWidget(frmModel, this.fieldId);
    Object value = widget.getValue();
    if (value != null && convertor != null) {
      value = convertor.convertToString(value, convertorLocale, null);
    }

    Object oldValue = jxpc.getValue(this.xpath);
    if (getLogger().isDebugEnabled()) {
      getLogger().debug("value= " + value + " -- oldvalue=" + oldValue);
    }

    boolean update = false;

    if ((value == null && oldValue != null) || value != null && !value.equals(oldValue)) {
      // first update the value itself
      jxpc.createPathAndSetValue(this.xpath, value);

      // now perform any other bindings that need to be performed when the value is updated
      JXPathContext subContext = null;
      try {
        subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
      } catch (JXPathException e) {
        // if the value has been set to null and the underlying model is a bean, then
        // JXPath will not be able to create a relative context
        if (getLogger().isDebugEnabled()) {
          getLogger()
              .debug("(Ignorable) problem binding field " + widget.getRequestParameterName(), e);
        }
      }
      if (subContext != null) {
        this.updateBinding.saveFormToModel(frmModel, subContext);
      }

      update = true;
    }

    if (getLogger().isDebugEnabled()) {
      getLogger()
          .debug("done saving " + this + " -- value= " + value + " -- on-update == " + update);
    }
  }
Beispiel #19
0
  static {
    System.setProperty(
        JXPathContextFactory.FACTORY_NAME_PROPERTY,
        OpenVPMSContextFactoryReferenceImpl.class.getName());

    // set the extended type converter
    TypeUtils.setTypeConverter(new OpenVPMSTypeConverter());

    // now just add the default functions
    functions.addFunctions(JXPathContext.newContext(new Object()).getFunctions());
  }
  protected void setUp() throws Exception {
    bean = new RecursiveBean("zero");
    RecursiveBean bean1 = new RecursiveBean("one");
    RecursiveBean bean2 = new RecursiveBean("two");
    RecursiveBean bean3 = new RecursiveBean("three");
    bean.setFirst(bean1);
    bean1.setFirst(bean2);
    bean2.setFirst(bean1);
    bean2.setSecond(bean3);

    context = JXPathContext.newContext(null, bean);
  }
  /**
   * Looks for a policy node at the specified contextual location for the specified object.
   *
   * <p>If a policy node that contains the object name is not found, a search is also done for the
   * default policy for all objects, with a special name ('*').
   *
   * @param xpathContext The XPath context around the agent configuration XML document
   * @param currentPointer A pointer to a particular node in the document to start searching from,
   *     such as a <code>&lt;zone&gt;</code>, <code>&lt;template&gt;</code>, or <code>&lt;agent&gt;
   *     </code> node.
   * @param policyPath The subPath, such as "requestPolicy"
   * @param objectName
   * @return
   */
  private Element findPolicy(
      JXPathContext xpathContext, Pointer currentPointer, String policyPath, String objectName) {

    if (currentPointer != null && currentPointer.getNode() != null) {
      String objectPolicyPath =
          "policy/" + policyPath + "/object[contains(@name,'" + objectName + "')]";
      JXPathContext zoneContext = xpathContext.getRelativeContext(currentPointer);
      Element zonePolicy = (Element) zoneContext.selectSingleNode(objectPolicyPath);
      if (zonePolicy != null) {
        return zonePolicy;
      }

      // Look for default policy for all objects at the zone level
      zonePolicy =
          (Element) zoneContext.selectSingleNode("policy/" + policyPath + "/object[@name='*']");
      if (zonePolicy != null) {
        return zonePolicy;
      }
    }
    return null;
  }
Beispiel #22
0
  public void saveDefinition(String[] file, String jsonString, IPentahoSession userSession)
      throws Exception {

    JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonString);
    JXPathContext.newContext(json);

    switch (RepositoryAccess.getRepository(userSession)
        .publishFile(file[0], file[1], json.toString().getBytes("UTF-8"), true)) {
      case FAIL:
        logger.error("Could not save definition " + StringUtils.join(file, "/"));
    }
  }
  /**
   * Look for the specified policy element, using an XPath traversal of zone, template, and agent
   * nodes
   *
   * @param zoneId The zoneId to retrieve policy for
   * @param policySubPath The path of the policy to retrieve, such as "requestPolicy" or
   *     "eventPolicy/transmitPolicy"
   * @param objectName The object type to retrieve policy for
   * @return
   */
  private Element getPolicyElement(String zoneId, String policySubPath, String objectName) {
    if (fConfig != null) {
      JXPathContext xpathContext =
          JXPathContext.newContext(fConfig.getDocument().getDocumentElement());
      xpathContext.setLenient(true);

      // Look first, for policy located under the particular zone node
      Pointer currentPointer = xpathContext.getPointer("zone[@id='" + zoneId + "']");
      if (currentPointer != null && currentPointer.getNode() != null) {
        Element policyNode = findPolicy(xpathContext, currentPointer, policySubPath, objectName);
        if (policyNode != null) {
          return policyNode;
        }
        // No policy for this object found at the zone level, search for policy under the
        // template
        Element zoneNode = (Element) currentPointer.getNode();
        String templateId = zoneNode.getAttribute("template");
        if (templateId != null) {
          currentPointer = xpathContext.getPointer("template[@id='" + templateId + "']");
          policyNode = findPolicy(xpathContext, currentPointer, policySubPath, objectName);
          if (policyNode != null) {
            return policyNode;
          }
        }
      }

      // Finally, look at the root agent element
      currentPointer = xpathContext.getContextPointer();
      return findPolicy(xpathContext, currentPointer, policySubPath, objectName);
    }
    return null;
  }
  private void testPathValue(QName commandName, String path, String expectedValue)
      throws Exception {
    // Get the command.
    Command command = catalog.getCommand(commandName);

    // execute the command.
    command.execute(context);

    // Get the result.
    String value = (String) context.getValue(path, String.class);

    assertEquals("The expected value for " + path + " failed.", expectedValue, value);
  }
  @Override
  public void process(JCas aJCas) throws AnalysisEngineProcessException {
    CAS cas = aJCas.getCas();

    for (AnnotationFS cover : CasUtil.select(cas, CasUtil.getAnnotationType(cas, annotationType))) {

      // If there is a constraint, check if it matches
      if (constraint != null) {
        JXPathContext ctx = JXPathContext.newContext(cover);
        boolean match = ctx.iterate(constraint).hasNext();
        if (!match) {
          continue;
        }
      }

      // If the target type is a token, use it directly, otherwise select the covered tokens
      Collection<Token> tokens;
      if (cover instanceof Token) {
        tokens = Collections.singleton((Token) cover);
      } else {
        tokens = JCasUtil.selectCovered(aJCas, Token.class, cover);
      }

      for (Token token : tokens) {
        try {
          String semanticField = semanticFieldResource.getSemanticTag(token);
          SemanticField semanticFieldAnnotation =
              new SemanticField(aJCas, token.getBegin(), token.getEnd());
          semanticFieldAnnotation.setValue(semanticField);
          semanticFieldAnnotation.addToIndexes();
        } catch (ResourceAccessException e) {
          throw new AnalysisEngineProcessException(e);
        }
      }
    }
  }
 /**
  * @param androidManifestFile
  * @return
  * @throws MojoExecutionException
  */
 protected String extractPackageNameFromAndroidManifest(File androidManifestFile)
     throws MojoExecutionException {
   final URL xmlURL;
   try {
     xmlURL = androidManifestFile.toURI().toURL();
   } catch (MalformedURLException e) {
     throw new MojoExecutionException(
         "Error while trying to figure out package name from inside AndroidManifest.xml file "
             + androidManifestFile,
         e);
   }
   final DocumentContainer documentContainer = new DocumentContainer(xmlURL);
   final Object packageName =
       JXPathContext.newContext(documentContainer).getValue("manifest/@package", String.class);
   return (String) packageName;
 }
 /**
  * @param c Company to cut salary
  * @param condition condition for cutting salary. The condition works on the Employee attributes
  *     salary, name and address. Use <a href="http://www.w3schools.com/xpath/xpath_operators.asp"
  *     >w3schools-operators</a> and <a href="http://www.w3schools.com/xpath/xpath_examples.asp"
  *     >w3schools-examples</a> as reference. Example: "salary>2000 and name!='Koblenz'"
  * @exception JXPathInvalidSyntaxException if condition is empty or is only whitespace
  */
 @SuppressWarnings("unchecked")
 public static void conditionedCut(Company c, String condition)
     throws JXPathInvalidSyntaxException {
   JXPathContext con = JXPathContext.newContext(c);
   ArrayList<Employee> es = new ArrayList<Employee>();
   es.addAll(con.selectNodes("//employees[" + condition + "]"));
   es.addAll(con.selectNodes("//manager[" + condition + "]"));
   // for (Employee e : es)
   // e.setSalary(e.getSalary() / 2);
   con = JXPathContext.newContext(es);
   for (int i = 1; i <= es.size(); i++) {
     con.setValue("@salary[" + i + "]", (Double) con.getValue("@salary[" + i + "]") / 2);
   }
 }
Beispiel #28
0
  public MobileDashboard(
      IParameterProvider pathParams, DashboardDesignerContentGenerator generator) {
    super(pathParams, generator);
    IPentahoSession userSession = PentahoSessionHolder.getSession();
    final ISolutionRepository solutionRepository =
        PentahoSystem.get(ISolutionRepository.class, userSession);

    final String absRoot =
        pathParams.hasParameter("root")
            ? !pathParams.getParameter("root").toString().isEmpty()
                ? "http://" + pathParams.getParameter("root").toString()
                : ""
            : "";
    final boolean absolute =
        (!absRoot.isEmpty())
            || pathParams.hasParameter("absolute")
                && pathParams.getParameter("absolute").equals("true");

    final RenderMobileLayout layoutRenderer = new RenderMobileLayout();
    final RenderComponents componentsRenderer = new RenderComponents();

    try {
      final JSONObject json =
          (JSONObject)
              JsonUtils.readJsonFromInputStream(
                  solutionRepository.getResourceInputStream(dashboardLocation, true));

      json.put("settings", getWcdf().toJSON());
      final JXPathContext doc = JXPathContext.newContext(json);

      final StringBuilder dashboardBody = new StringBuilder();

      dashboardBody.append(layoutRenderer.render(doc));
      dashboardBody.append(componentsRenderer.render(doc));

      // set all dashboard members
      this.content = replaceTokens(dashboardBody.toString(), absolute, absRoot);

      this.header = renderHeaders(pathParams, this.content.toString());
      this.loaded = new Date();
    } catch (Exception e) {
      logger.error(e);
    }
  }
 /**
  * Attempts to find the instrumentation test runner from inside the AndroidManifest.xml file.
  *
  * @param androidManifestFile the AndroidManifest.xml file to inspect.
  * @return the instrumentation test runner declared in AndroidManifest.xml, or {@code null} if it
  *     is not declared.
  * @throws MojoExecutionException
  */
 protected String extractInstrumentationRunnerFromAndroidManifest(File androidManifestFile)
     throws MojoExecutionException {
   final URL xmlURL;
   try {
     xmlURL = androidManifestFile.toURI().toURL();
   } catch (MalformedURLException e) {
     throw new MojoExecutionException(
         "Error while trying to figure out instrumentation runner from inside AndroidManifest.xml file "
             + androidManifestFile,
         e);
   }
   final DocumentContainer documentContainer = new DocumentContainer(xmlURL);
   final Object instrumentationRunner;
   try {
     instrumentationRunner =
         JXPathContext.newContext(documentContainer)
             .getValue("manifest//instrumentation/@android:name", String.class);
   } catch (JXPathNotFoundException e) {
     return null;
   }
   return (String) instrumentationRunner;
 }
Beispiel #30
0
  public boolean execute(JXPathContext context) throws Exception {
    QName variableName = getName(context);
    Object variableValue = null;

    if (hasSelect()) {
      variableValue = getSelect(context);
    } else if (hasSelectNodes()) {
      variableValue = getSelectNodes(context);
    } else if (hasSelectSingleNode()) {
      variableValue = getSelectSingleNode(context);
    } else {
      throw new Exception(
          "Variable '"
              + variableName
              + "' must have a select attribute (select, select-nodes, or select-single-node)");
    }

    // get the scope.
    Scope scope = getScope(context);

    if (log.isDebugEnabled()) {
      log.debug(
          "Setting variable name '"
              + variableName
              + "' to value '"
              + variableValue
              + "' in scope '"
              + scope
              + "'.");
    }

    // declare the variable.
    ((ScopedQNameVariables) context.getVariables())
        .declareVariable(variableName, variableValue, scope);

    // return false and allow other chains to execute.
    return false;
  }