public OptionSelectionDetailsType(Node node) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Node childNode = null;
    NodeList nodeList = null;
    childNode = (Node) xpath.evaluate("OptionSelection", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.optionSelection = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("Price", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.price = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("OptionType", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.optionType = OptionTypeListType.fromValue(childNode.getTextContent());
    }
    nodeList = (NodeList) xpath.evaluate("PaymentPeriod", node, XPathConstants.NODESET);
    if (nodeList != null && nodeList.getLength() > 0) {
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node subNode = nodeList.item(i);
        this.paymentPeriod.add(new InstallmentDetailsType(subNode));
      }
    }
  }
 private NodeList getNodeList(Object element, String xPathExp) throws XPathExpressionException {
   XPathFactory factory = XPathFactory.newInstance();
   XPath xpath = factory.newXPath();
   XPathExpression expr = xpath.compile(xPathExp);
   Object obj = expr.evaluate(element, XPathConstants.NODESET);
   return obj instanceof NodeList ? (NodeList) obj : null;
 }
 /**
  * Failure test for the method <code>handleMessage</code>.<br>
  * when ExpirationTime not valid date time value
  *
  * @throws Exception to JUnit.
  */
 @Test(expected = IllegalArgumentException.class)
 public void test_handleMessageFail2() throws Exception {
   clearDB();
   loadData();
   User user = getTestUser();
   user.setRole(entityManager.find(Role.class, "1"));
   user = userService.create(user);
   entityManager.flush();
   User user1 = getTestUser();
   user1.setRole(entityManager.find(Role.class, "1"));
   user1 = userService.create(user1);
   entityManager.flush();
   Connection connection = jmsTemplate.getConnectionFactory().createConnection();
   try {
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     TextMessage message = session.createTextMessage("");
     Document doc = getDataRequestDocument(request);
     doc.getElementsByTagName("ExpirationTime").item(0).setTextContent("invalida date");
     XPathFactory xpathFactory = XPathFactory.newInstance();
     XPath xpath = xpathFactory.newXPath();
     VelocityContext templateContext = new VelocityContext();
     instance.handleMessage(message, user1, doc, xpath, templateContext);
   } finally {
     connection.close();
   }
 }
Example #4
0
 protected Object exec(Object[] args, Context context) {
   try {
     int nargs = args.length;
     if (nargs == 2) {
       Object target = args[0];
       String expr = (String) args[1];
       XPath xpath = XPathFactory.newInstance().newXPath();
       if (target instanceof Node) {
         return xpath.evaluate(expr, target, XPathConstants.NODESET);
       } else {
         return xpath.evaluate(expr, Util.inputSource(target, context), XPathConstants.NODESET);
       }
     } else if (nargs == 3) {
       Object target = args[0];
       String expr = (String) args[1];
       XPath xpath = XPathFactory.newInstance().newXPath();
       if (target instanceof Node) {
         return xpath.evaluate(expr, target, XPathConstants.NODESET);
       } else {
         return xpath.evaluate(expr, Util.inputSource(target, context), XPathConstants.NODESET);
       }
     } else {
       undefined(args, context);
       return null;
     }
   } catch (Exception e) {
     throw new PnutsException(e, context);
   }
 }
Example #5
0
  public String extractInfoObjectIdentifier(String infoObjectResponse) {

    String reportId = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // dbf.setNamespaceAware(true);
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile("//info-object");
      Object result = expr.evaluate(doc, XPathConstants.NODESET);

      NodeList nodes = (NodeList) result;
      Node item = nodes.item(0);
      if (item != null) {
        NamedNodeMap attributesMap = item.getAttributes();
        Node idAttribute = attributesMap.getNamedItem("id");
        reportId = idAttribute.getNodeValue();
      }

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return reportId;
  }
 /**
  * Failure test for the method <code>handleMessage</code>.<br>
  * when request partner id not exist
  *
  * @throws Exception to JUnit.
  */
 @Test(expected = EntityNotFoundException.class)
 public void test_handleMessageFail1() throws Exception {
   clearDB();
   loadData();
   User user = getTestUser();
   user.setRole(entityManager.find(Role.class, "1"));
   user = userService.create(user);
   entityManager.flush();
   User user1 = getTestUser();
   user1.setRole(entityManager.find(Role.class, "1"));
   user1 = userService.create(user1);
   entityManager.flush();
   Connection connection = jmsTemplate.getConnectionFactory().createConnection();
   try {
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     TextMessage message = session.createTextMessage("");
     request.setRequestedPartners(Arrays.asList("not exist Id"));
     Document doc = getDataRequestDocument(request);
     XPathFactory xpathFactory = XPathFactory.newInstance();
     XPath xpath = xpathFactory.newXPath();
     VelocityContext templateContext = new VelocityContext();
     instance.handleMessage(message, user1, doc, xpath, templateContext);
   } finally {
     connection.close();
   }
 }
 protected List<String> getDistributionFilenames() {
   File distributionMPFile = new File(distributionMPDir, PACKAGES_XML);
   List<String> md5Filenames = new ArrayList<String>();
   // Try to get md5 files from packages.xml
   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
   docFactory.setNamespaceAware(true);
   try {
     DocumentBuilder builder = docFactory.newDocumentBuilder();
     Document doc = builder.parse(distributionMPFile);
     XPathFactory xpFactory = XPathFactory.newInstance();
     XPath xpath = xpFactory.newXPath();
     XPathExpression expr = xpath.compile("//package/@md5");
     NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
     for (int i = 0; i < nodes.getLength(); i++) {
       String md5 = nodes.item(i).getNodeValue();
       if ((md5 != null) && (md5.length() > 0)) {
         md5Filenames.add(md5);
       }
     }
   } catch (Exception e) {
     // Parsing failed - return empty list
     log.error("Failed parsing " + distributionMPFile, e);
     return new ArrayList<String>();
   }
   return md5Filenames;
 }
Example #8
0
  @Override
  public Layer load(Element elem, ImportSupport support, ProgressMonitor progressMonitor)
      throws IOException, IllegalDataException {
    String version = elem.getAttribute("version");
    if (!"0.1".equals(version)) {
      throw new IllegalDataException(
          tr(
              "Version ''{0}'' of meta data for osm data layer is not supported. Expected: 0.1",
              version));
    }
    try {
      XPathFactory xPathFactory = XPathFactory.newInstance();
      XPath xpath = xPathFactory.newXPath();
      XPathExpression fileExp = xpath.compile("file/text()");
      String fileStr = (String) fileExp.evaluate(elem, XPathConstants.STRING);
      if (fileStr == null || fileStr.isEmpty()) {
        throw new IllegalDataException(
            tr("File name expected for layer no. {0}", support.getLayerIndex()));
      }

      OsmImporter importer = new OsmImporter();
      try (InputStream in = support.getInputStream(fileStr)) {
        OsmImporter.OsmImporterData importData =
            importer.loadLayer(
                in, support.getFile(fileStr), support.getLayerName(), progressMonitor);

        support.addPostLayersTask(importData.getPostLayerTask());
        return importData.getLayer();
      }
    } catch (XPathExpressionException e) {
      throw new RuntimeException(e);
    }
  }
Example #9
0
  /** @{inheritDoc} */
  @Override
  protected void execute() {
    logger.trace("Connecting to {}" + baseURL);

    clearState();

    String xmlDoc = fetchStateFromController();

    if (xmlDoc == null) {
      return;
    }

    for (AutelisBindingProvider provider : providers) {
      for (String itemName : provider.getItemNames()) {
        Item item = provider.getItem(itemName);
        String config = provider.getAutelisBindingConfigString(itemName);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
          InputSource is = new InputSource(new StringReader(xmlDoc));
          String value = xpath.evaluate("response/" + config.replace('.', '/'), is);
          State state = toState(item.getClass(), value);
          State oldState = stateMap.put(itemName, state);
          if (!state.equals(oldState)) {
            logger.debug("updating item {} with state {}", itemName, state);
            eventPublisher.postUpdate(itemName, state);
          }
        } catch (XPathExpressionException e) {
          logger.warn("could not parse xml", e);
        }
      }
    }
  }
  public List<String> getOriginCatalogs() {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    List<String> catalogs = new ArrayList<String>();
    try {
      XPathExpression expr = xpath.compile("//Resolver");

      NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {
        XPathExpression hasAliasExp = xpath.compile("./alias");
        NodeList aliases = (NodeList) hasAliasExp.evaluate(nodes.item(i), XPathConstants.NODESET);
        if (aliases.getLength() > 0) {
          XPathExpression nameAttribute = xpath.compile("@name");
          String name = (String) nameAttribute.evaluate(nodes.item(i), XPathConstants.STRING);
          catalogs.add(name);
        }
      }

    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return catalogs;
  }
  public PositionTester(String uri, int line, int col)
      throws IOException, SAXException, XPathExpressionException {

    InputStream is = new FileInputStream(new File(uri));
    Document document = PositionalXMLReader.readXML(is);

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    XPathExpression expr = xpath.compile("//*");
    Object result = expr.evaluate(document, XPathConstants.NODESET);

    NodeList allNodes = (NodeList) result;
    int i = 0;
    Node node;
    while (allNodes.item(i) != null) {
      node = allNodes.item(i);
      i++;
      int ln = (Integer) node.getUserData("lineNumber");
      int cn = (Integer) node.getUserData("columnNumber");
      if (line == ln && col == cn) {
        element = node;
        break;
      }
    }
  }
  public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath)
      throws XPathExpressionException {

    List<String> list = new ArrayList<String>();
    XPathFactory factory = XPathFactory.newInstance();

    // 2. Use the XPathFactory to create a new XPath object
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(nsc);

    // 3. Compile an XPath string into an XPathExpression
    XPathExpression expression = xpath.compile(exprString);

    // 4. Evaluate the XPath expression on an input document
    Node result =
        (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE);

    String svcName = null;
    NamedNodeMap attMap = result.getAttributes();
    Node att = attMap.getNamedItem("group");
    if (att != null) svcName = att.getNodeValue();
    if (result != null) {
      list.add(result.getNodeName());
      list.add(result.getTextContent());
      list.add(svcName);
    }
    factory = null;
    xpath = null;
    expression = null;
    result = null;
    attMap = null;
    att = null;
    return list;
  }
Example #13
0
 {
   System.setProperty(
       XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI,
       "net.sf.saxon.xpath.XPathFactoryImpl");
   xPath = XPathFactory.newInstance().newXPath();
   System.err.println("SaxonXPathParser: xpath: " + XPathFactory.newInstance().getClass());
 }
 @Override
 public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
   super.visitMethodCallExpression(expression);
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length == 0) {
     return;
   }
   final PsiExpression xpathArgument = arguments[0];
   if (!ExpressionUtils.hasStringType(xpathArgument)) {
     return;
   }
   if (!PsiUtil.isConstantExpression(xpathArgument)) {
     return;
   }
   final PsiType type = xpathArgument.getType();
   if (type == null) {
     return;
   }
   final String value = (String) ConstantExpressionUtil.computeCastTo(xpathArgument, type);
   if (value == null) {
     return;
   }
   if (!callTakesXPathExpression(expression)) {
     return;
   }
   final XPathFactory xpathFactory = XPathFactory.newInstance();
   final XPath xpath = xpathFactory.newXPath();
   //noinspection UnusedCatchParameter,ProhibitedExceptionCaught
   try {
     xpath.compile(value);
   } catch (XPathExpressionException ignore) {
     registerError(xpathArgument);
   }
 }
 private void checkBomVersionInPom(String xml) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   try {
     builder = factory.newDocumentBuilder();
     doc = builder.parse(new InputSource(new StringReader(xml)));
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression expr = null;
   String bom_version = null;
   try {
     expr = xpath.compile("/project/properties/version.jboss.bom");
     bom_version = (String) expr.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   assertEquals(
       "jboss bom version in pom differs from the one given by wizard", version, bom_version);
 }
 private void initXpath() {
   factory = XPathFactory.newInstance();
   namespaceContext = new NamespaceContextImpl();
   namespaceContext.startPrefixMapping("saml1", "urn:oasis:names:tc:SAML:1.0:assertion");
   xpath = factory.newXPath();
   xpath.setNamespaceContext(namespaceContext);
 }
 public MergePoint(MergeHandler handler, Document doc1, Document doc2) {
   this.handler = handler;
   this.doc1 = doc1;
   this.doc2 = doc2;
   XPathFactory factory = XPathFactory.newInstance();
   xPath = factory.newXPath();
 }
Example #18
0
 /**
  * Evaluate an XPath string and return true if the output is to be included or not.
  *
  * @param contextNode The node to start searching from.
  * @param xpathnode The XPath node
  * @param str The XPath expression
  * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
  */
 public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
     throws TransformerException {
   if (!str.equals(xpathStr) || xpathExpression == null) {
     if (xpf == null) {
       xpf = XPathFactory.newInstance();
       try {
         xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
       } catch (XPathFactoryConfigurationException ex) {
         throw new TransformerException(ex);
       }
     }
     XPath xpath = xpf.newXPath();
     xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
     xpathStr = str;
     try {
       xpathExpression = xpath.compile(xpathStr);
     } catch (XPathExpressionException ex) {
       throw new TransformerException(ex);
     }
   }
   try {
     return (Boolean) xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN);
   } catch (XPathExpressionException ex) {
     throw new TransformerException(ex);
   }
 }
  @Override
  public void addAssociation(
      String associationName, String workflowId, String eventId, String condition)
      throws WorkflowException {

    if (StringUtils.isBlank(workflowId)) {
      log.error("Null or empty string given as workflow id to be associated to event.");
      throw new InternalWorkflowException("Service alias cannot be null");
    }
    if (StringUtils.isBlank(eventId)) {
      log.error("Null or empty string given as 'event' to be associated with the service.");
      throw new InternalWorkflowException("Event type cannot be null");
    }

    if (StringUtils.isBlank(condition)) {
      log.error(
          "Null or empty string given as condition expression when associating "
              + workflowId
              + " to event "
              + eventId);
      throw new InternalWorkflowException("Condition cannot be null");
    }

    // check for xpath syntax errors
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
      xpath.compile(condition);
      workflowDAO.addAssociation(associationName, workflowId, eventId, condition);
    } catch (XPathExpressionException e) {
      log.error("The condition:" + condition + " is not an valid xpath expression.", e);
      throw new WorkflowRuntimeException("The condition is not a valid xpath expression.");
    }
  }
  private String fromXmlToColor(String xml) {
    String result = BLUE;
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = null;
    try {
      builder = domFactory.newDocumentBuilder();

      Document document = builder.parse(new InputSource(new StringReader(xml)));

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile("//color");

      Object n = expr.evaluate(document, XPathConstants.NODESET);
      NodeList nodes = (NodeList) n;
      if (nodes.getLength() > 0) {
        result = (String) nodes.item(0).getTextContent();
      }

    } catch (Exception e) {
      System.err.println("fromXmlToColor:" + e);
    }
    return result;
  }
  public GetAuthDetailsResponseDetailsType(Node node) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Node childNode = null;
    NodeList nodeList = null;
    childNode = (Node) xpath.evaluate("FirstName", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.FirstName = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("LastName", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.LastName = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("Email", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.Email = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("PayerID", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.PayerID = childNode.getTextContent();
    }
  }
Example #22
0
 public XformParserODK() {
   XPathFactory xPathFactory = XPathFactory.newInstance();
   this.xPath = xPathFactory.newXPath();
   SimpleNamespaceContext namespaces = new SimpleNamespaceContext();
   namespaces.setBindings(NAMESPACE_MAP);
   this.xPath.setNamespaceContext(namespaces);
 }
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  protected void buildWritePaths(org.w3c.dom.Node dataFileCacheNode) {
    javax.xml.xpath.XPathFactory pathFactory = javax.xml.xpath.XPathFactory.newInstance();
    javax.xml.xpath.XPath pathFinder = pathFactory.newXPath();

    try {
      org.w3c.dom.NodeList locationNodes =
          (org.w3c.dom.NodeList)
              pathFinder.evaluate(
                  "/dataFileStore/writeLocations/location",
                  dataFileCacheNode.getFirstChild(),
                  javax.xml.xpath.XPathConstants.NODESET);
      for (int i = 0; i < locationNodes.getLength(); i++) {
        org.w3c.dom.Node location = locationNodes.item(i);
        String prop = pathFinder.evaluate("@property", location);
        String wwDir = pathFinder.evaluate("@wwDir", location);
        String append = pathFinder.evaluate("@append", location);
        String create = pathFinder.evaluate("@create", location);

        String path = buildLocationPath(prop, append, wwDir);
        if (path == null) {
          Logging.logger()
              .log(
                  Level.WARNING,
                  "FileStore.LocationInvalid",
                  prop != null ? prop : Logging.getMessage("generic.Unknown"));
          continue;
        }

        Logging.logger().log(Level.FINER, "FileStore.AttemptingWriteDir", path);
        java.io.File pathFile = new java.io.File(path);
        if (!pathFile.exists()
            && create != null
            && (create.contains("t") || create.contains("T"))) {
          Logging.logger().log(Level.FINER, "FileStore.MakingDirsFor", path);
          pathFile.mkdirs();
        }

        if (pathFile.isDirectory() && pathFile.canWrite() && pathFile.canRead()) {
          Logging.logger().log(Level.FINER, "FileStore.WriteLocationSuccessful", path);
          this.writeLocation = new StoreLocation(pathFile);

          // Remove the writable location from search path if it already exists.
          StoreLocation oldLocation = this.storeLocationFor(path);
          if (oldLocation != null) this.readLocations.remove(oldLocation);

          // Writable location is always first in search path.
          this.readLocations.add(0, this.writeLocation);

          break; // only need one
        }
      }
    } catch (javax.xml.xpath.XPathExpressionException e) {
      String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile");
      Logging.logger().severe(message);
      throw new IllegalStateException(message, e);
    }
  }
Example #24
0
  /**
   * Creates a new PoolElement with the specified attributes.
   *
   * @param id Id of the element.
   * @param client XML-RPC Client.
   */
  protected PoolElement(int id, Client client) {
    if (xpath == null) {
      XPathFactory factory = XPathFactory.newInstance();
      xpath = factory.newXPath();
    }

    this.id = id;
    this.client = client;
  }
Example #25
0
  public XMLParser(String filePath) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    doc = builder.parse(filePath);

    XPathFactory factory = XPathFactory.newInstance();
    xPathInstance = factory.newXPath();
  }
Example #26
0
 private void commonConstructor(
     boolean validation, Properties variables, EntityResolver entityResolver) {
   this.validation = validation;
   this.entityResolver = entityResolver;
   this.variables = variables;
   // 共通构造函数,除了把参数都设置到实例变量里面去以外,还初始化了XPath
   XPathFactory factory = XPathFactory.newInstance();
   this.xpath = factory.newXPath();
 }
public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {

  private static final XPathFactory FACTORY = XPathFactory.newInstance();
  private final String xpathExpression;
  private final DocumentBuilder builder;
  private final XPath xpath = FACTORY.newXPath();

  public XalanXPathEvaluator(String xpathExpression, DocumentBuilder builder) throws Exception {
    this.xpathExpression = xpathExpression;
    if (builder != null) {
      this.builder = builder;
    } else {
      throw new RuntimeException("No document builder available");
    }
  }

  public boolean evaluate(Message message) throws JMSException {
    if (message instanceof TextMessage) {
      String text = ((TextMessage) message).getText();
      return evaluate(text);
    } else if (message instanceof BytesMessage) {
      BytesMessage bm = (BytesMessage) message;
      byte data[] = new byte[(int) bm.getBodyLength()];
      bm.readBytes(data);
      return evaluate(data);
    }
    return false;
  }

  private boolean evaluate(byte[] data) {
    try {
      InputSource inputSource = new InputSource(new ByteArrayInputStream(data));
      Document inputDocument = builder.parse(inputSource);
      return ((Boolean) xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN))
          .booleanValue();
    } catch (Exception e) {
      return false;
    }
  }

  private boolean evaluate(String text) {
    try {
      InputSource inputSource = new InputSource(new StringReader(text));
      Document inputDocument = builder.parse(inputSource);
      return ((Boolean) xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN))
          .booleanValue();
    } catch (Exception e) {
      return false;
    }
  }

  @Override
  public String toString() {
    return xpathExpression;
  }
}
Example #28
0
  /**
   * Creates a new PoolElement from the xml provided.
   *
   * @param client XML-RPC Client.
   * @param xmlElement XML representation of the element.
   */
  protected PoolElement(Node xmlElement, Client client) {
    if (xpath == null) {
      XPathFactory factory = XPathFactory.newInstance();
      xpath = factory.newXPath();
    }

    this.xml = xmlElement;
    this.client = client;
    this.id = Integer.parseInt(xpath("id"));
  }
Example #29
0
 public XmlNodeList SelectNodes(String string) {
   try {
     XPathFactory factory = XPathFactory.newInstance();
     XPath xPath = factory.newXPath();
     Object o = xPath.evaluate(string, node, XPathConstants.NODESET);
     return new XmlNodeList((NodeList) o);
   } catch (XPathExpressionException e) {
     throw new RuntimeException("Failed to evaluate xpath: " + string, e);
   }
 }
Example #30
0
    private static void validateXPath(String x) {
      XPathFactory factory = XPathFactory.newInstance();
      javax.xml.xpath.XPath validate = factory.newXPath();

      try {
        validate.compile(x);
      } catch (XPathExpressionException e) {
        throw new MalformedXmlElement("Invalid XPath: " + x);
      }
    }