コード例 #1
0
ファイル: Majn.java プロジェクト: kordirko/test
  public static void main(String[] args)
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
          TransformerFactoryConfigurationError, TransformerException {
    DocumentBuilder bud = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    InputStream inp = new ByteArrayInputStream(xml.getBytes());

    Document doc = bud.parse(inp);

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//Person/PostalCode");

    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
      System.out.println(nodes.item(i).getTextContent());
      nodes.item(i).setTextContent("Ala ma kota " + i);
    }

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    StringWriter bufor = new StringWriter();
    xformer.transform(new DOMSource(doc), new StreamResult(bufor));
    System.out.println("===================");
    System.out.println(bufor.toString());
  }
コード例 #2
0
  @Test
  public void testFieldHasMatchingUserValues() throws Exception {
    LOG.info("testFieldHasMatchingUserValues");
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc = db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML));
    // enumerate all fields
    final String fieldDefs = "/edlContent/edl/field/display/values";
    NodeList nodes = (NodeList) xpath.evaluate(fieldDefs, doc, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      String name = (String) xpath.evaluate("../../@name", node, XPathConstants.STRING);
      LOG.debug("Name: " + name);
      LOG.debug("Value: " + node.getFirstChild().getNodeValue());
      final String expr =
          "/edlContent/data/version[@current='true']/fieldEntry[@name=current()/../../@name and value=current()]";
      NodeList matchingUserValues = (NodeList) xpath.evaluate(expr, node, XPathConstants.NODESET);
      LOG.debug(matchingUserValues + "");
      LOG.debug(matchingUserValues.getLength() + "");
      if ("gender".equals(name)) {
        assertTrue("Matching values > 0", matchingUserValues.getLength() > 0);
      }
      for (int j = 0; j < matchingUserValues.getLength(); j++) {
        LOG.debug(matchingUserValues.item(j).getFirstChild().getNodeValue());
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b())
            .goodG2B_source(request, response);

    final String xmldoc =
        "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";

    /* assume username||password as source */
    String[] tokens = data.split("||");
    if (tokens.length < 2) {
      return;
    }
    String uname = tokens[0];
    String pword = tokens[1];

    /* build xpath */
    XPath xp = XPathFactory.newInstance().newXPath();
    InputSource inxml = new InputSource(xmldoc);
    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
     * 	The user input should be canonicalized before validation.
     */
    /* FLAW: user input is used without validate */
    String query =
        "//users/user[name/text()='"
            + uname
            + "' and pass/text()='"
            + pword
            + "']"
            + "/secret/text()";
    String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
  }
コード例 #4
0
 @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);
   }
 }
コード例 #5
0
  public NodeList getOQasNodeList()
      throws SAXException, ParserConfigurationException, XPathExpressionException {
    NodeList result = null;
    if (oqUrl == null) {
      logger.warn("OQ.url not found. Synchronization impossible.");
      trace.append("Синхронизация невозможна: OQ.url не указан.");
      return result;
    }
    try {
      URLConnection oqc = oqUrl.openConnection();
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true);
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document doc = builder.parse(oqc.getInputStream());
      XPath xpath = XPathFactory.newInstance().newXPath();
      XPathExpression expr = xpath.compile("/root/projects/project");
      result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (IOException e) { // обрабатываем только IOException - остальные выбрасываем наверх
      logger.error("oq project sync error: ", e);
      trace
          .append(
              "Синхронизация прервана из-за ошибки ввода/вывода при попытке получить и прочитать файл "
                  + "синхронизации: ")
          .append(e.getMessage())
          .append("\n");
    }

    return result;
  }
コード例 #6
0
ファイル: XML.java プロジェクト: chen0031/hawkular-btm
  /**
   * This method evaluates the predicate based on the xpath expression on the supplied node.
   *
   * @param xpath The xpath expression
   * @param node The node
   * @return The result
   */
  public static boolean predicate(String xpath, Object node) {
    Node domNode = getNode(node);

    if (domNode == null) {
      log.severe("Unable to evaluate non DOM Node object");
      return false;
    }

    if (xpath == null) {
      log.severe("Predicate has not xpath expression");
      return false;
    }

    // TODO: HWKBTM-104 Investigate caching compiled xpath expressions
    try {
      xpath = getExpression(xpath);
      XPath xp = XPathFactory.newInstance().newXPath();
      Boolean result = (Boolean) xp.evaluate(xpath, domNode, XPathConstants.BOOLEAN);

      if (result != null) {
        return result;
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, "Failed to execute predicate xpath '" + xpath + "'", e);
    }

    return false;
  }
コード例 #7
0
ファイル: Replayer.java プロジェクト: HohoTest/iGUITAR
  /**
   * Get container window
   *
   * <p>
   *
   * @return String
   */
  private String getWindowName(String sWidgetID) {

    String sWindowName = null;
    // get widget ID
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    Object result;
    NodeList nodes;
    try {
      String xpathExpression =
          "/GUIStructure/GUI[Container//Property[Name=\""
              + GUITARConstants.ID_TAG_NAME
              + "\" and Value=\""
              + sWidgetID
              + "\"]]/Window/Attributes/Property[Name=\""
              + GUITARConstants.TITLE_TAG_NAME
              + "\"]/Value/text()";
      expr = xpath.compile(xpathExpression);
      result = expr.evaluate(docGUI, XPathConstants.NODESET);
      nodes = (NodeList) result;
      if (nodes.getLength() > 0) sWindowName = nodes.item(0).getNodeValue();
    } catch (XPathExpressionException e) {
      GUITARLog.log.error(e);
    }
    return sWindowName;
  }
コード例 #8
0
  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;
  }
コード例 #9
0
  private Node evaluateXPathNode(
      Node bindings, Node target, String expression, NamespaceContext namespaceContext) {
    NodeList nlst;
    try {
      xpath.setNamespaceContext(namespaceContext);
      nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      reportError(
          (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATION_ERROR(e.getMessage()), e);
      return null; // abort processing this <jaxb:bindings>
    }

    if (nlst.getLength() == 0) {
      reportError(
          (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NO_TARGET(expression));
      return null; // abort
    }

    if (nlst.getLength() != 1) {
      reportError(
          (Element) bindings,
          WsdlMessages.INTERNALIZER_X_PATH_EVAULATES_TO_TOO_MANY_TARGETS(
              expression, nlst.getLength()));
      return null; // abort
    }

    Node rnode = nlst.item(0);
    if (!(rnode instanceof Element)) {
      reportError(
          (Element) bindings,
          WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NON_ELEMENT(expression));
      return null; // abort
    }
    return rnode;
  }
コード例 #10
0
  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;
  }
コード例 #11
0
  /**
   * Extract an XML element.
   *
   * @param xpathExp
   * @param file
   * @return
   */
  private Document getDocFragment(String xpathExp, XmlMetadata file) {

    Document testDoc = null;

    try {
      XPath xpath = XPathFactory.newInstance().newXPath();
      Node node = (Node) xpath.evaluate(xpathExp, file.getParsedDocument(), XPathConstants.NODE);

      if (node != null) {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        String testStr = buffer.toString();
        LOG.debug("src string: " + testStr);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        testDoc =
            dBuilder.parse(new InputSource(new ByteArrayInputStream(testStr.getBytes("utf-8"))));
      }
    } catch (XPathExpressionException xee) {
      LOG.error("Invalid XPath expression: " + xpathExp);
    } catch (Exception e) {
      LOG.error("Error extracting XML content: ", e);
    }

    return testDoc;
  }
コード例 #12
0
 public static MediaNode create(final Node media, final XPath xpath) throws Exception {
   final String url = xpath.evaluate("./@url", media);
   final int bitrate = getBitrate(media, xpath);
   final String bootstrapInfoId = xpath.evaluate("./@bootstrapInfoId", media);
   final String href = xpath.evaluate("./@href", media);
   return new MediaNode(url, bitrate, bootstrapInfoId, href);
 }
コード例 #13
0
  /**
   * Initialize the GuideXML class with a local file XML path
   *
   * @param context the app context
   * @param guideId the guide identifier
   * @param path the local file name of the guide XML file
   */
  public GuideXML(Context context, String guideId, String path) {
    mContext = context;
    mGuideId = guideId;

    FileReader fr = null;
    try {
      fr = new FileReader(path);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    }
    InputSource inputSource = new InputSource(fr);

    mTagCounts = new HashMap<String, Integer>();
    mTags = new HashMap<String, Set<String>>();

    try {
      // Read root node so we won't re-parse the XML file every time we evaluate an XPath
      XPath xpath = XPathFactory.newInstance().newXPath();
      setRootNode((Node) xpath.evaluate("/", inputSource, XPathConstants.NODE));

      // Parse all taxon tags
      parseTags();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
コード例 #14
0
 public InternalDocColumnSchema getColumnSchema() {
   columnSchema = new InternalDocColumnSchemaImpl(numberOfColumns);
   XPath xpath = XPathFactory.newInstance().newXPath();
   for (Integer index : indexesTable.keySet()) {
     NodeList indexToColumnData = null;
     try {
       indexToColumnData =
           (NodeList)
               xpath.evaluate(
                   "//contact[count(*[@columnCounter="
                       + index
                       + "]) = "
                       + indexesTable.get(index).size()
                       + "][1]/*[@columnCounter="
                       + index
                       + "]",
                   compiledDoc,
                   XPathConstants.NODESET);
     } catch (XPathExpressionException ex) {
       Logger.getLogger(ReadCompiledDoc.class.getName()).log(Level.SEVERE, null, ex);
     }
     if (indexToColumnData == null) {
       System.err.println("Error while parsing compiled doc into column schema - errNo:4");
       return null;
     }
     int iterator = 0;
     for (Integer column : indexesTable.get(index)) {
       String type = ((Element) indexToColumnData.item(iterator)).getTagName();
       columnSchema.setCandidateType(column, type);
       columnSchema.setSelectedtypeType(column, type);
       iterator++;
     }
   }
   return columnSchema;
 }
コード例 #15
0
  public static void main(String[] args) {

    CodeExtractor myCode = new CodeExtractor(4);
    // myCode.parseFile("http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html");
    myCode.parseFile("http://www.javadeveloper.co.in/java-example/java-hashmap-example.html");

    String docString = myCode.getDoc();
    try {
      XPath xPath = XPathFactory.newInstance().newXPath();
      XPathExpression nodeXPathExpr =
          xPath.compile("/codesnippets/text | /codesnippets/sourcecode");
      InputSource inputSource = new InputSource(new ByteArrayInputStream(docString.getBytes()));

      NodeList allNodes = (NodeList) nodeXPathExpr.evaluate(inputSource, XPathConstants.NODESET);

      int nodeNumber = allNodes.getLength();
      System.out.println("Text Found:: " + nodeNumber + " nodes.");
      System.out.println("========================================");

      for (int i = 0; i < nodeNumber; i++) {
        Node node = allNodes.item(i);

        String content = node.getTextContent();
        // content = StringEscapeUtils.unescapeHtml(content).trim();
        System.out.println(node + ":--->:" + node.getNodeName());
        if (node.getTextContent() != null) System.out.println("--->" + content);
        System.out.println("========================================");
      }

    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
コード例 #16
0
  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();
    }
  }
コード例 #17
0
ファイル: XML.java プロジェクト: chen0031/hawkular-btm
  /**
   * This method evaluates the xpath expression on the supplied node. The result can either be a
   * document fragment, a text node value or null if the expression references a missing part of the
   * document.
   *
   * @param xpath The xpath expression
   * @param node The node
   * @return The result, or null if not found (which may be due to an expression error)
   */
  public static String evaluate(String xpath, Object node) {
    Node domNode = getNode(node);

    if (domNode == null) {
      log.severe("Unable to evaluate non DOM Node object");
      return null;
    }

    // If no xpath expression, then serialize
    if (xpath == null || xpath.trim().length() == 0) {
      return serialize(node);
    }

    // TODO: HWKBTM-104 Investigate caching compiled xpath expressions
    try {
      xpath = getExpression(xpath);
      XPath xp = XPathFactory.newInstance().newXPath();
      Node result = (Node) xp.evaluate(xpath, domNode, XPathConstants.NODE);

      if (result != null) {
        if (result.getNodeType() == Node.TEXT_NODE) {
          return result.getNodeValue();
        } else if (result.getNodeType() == Node.ATTRIBUTE_NODE) {
          return result.getNodeValue();
        }
        return serialize(result);
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, "Failed to evaluate xpath '" + xpath + "'", e);
    }

    return null;
  }
コード例 #18
0
  @Override
  protected String verifyWpsResponse(final String responseStr) throws Exception {
    final Document responseData = XmlDocumentBuilder.parse(responseStr, false);
    Assert.assertNotNull(responseData);
    // System.out.println(XmlDocumentBuilder.toString(responseData));

    XPath xpath = XmlDocumentBuilder.createXPath();
    String jobIdStr = null;
    try {
      Assert.assertEquals(processId, xpath.evaluate(".//Process/Identifier", responseData));
      NodeList returnedNodes = XPathAPI.selectNodeList(responseData, ".//ProcessOutputs/Output");
      Assert.assertEquals(1, returnedNodes.getLength());
      Assert.assertEquals(
          "jobId", xpath.evaluate(".//ProcessOutputs/Output/Identifier", responseData));
      Assert.assertEquals(
          "string",
          xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData/@dataType", responseData));
      jobIdStr = xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData", responseData);
      Assert.assertNotNull(UUID.fromString(jobIdStr));
    } catch (XPathExpressionException e) {
      Assert.fail("Error parsing response document: " + e.getMessage());
    }

    return jobIdStr;
  }
  public Location getLocationData() {
    Location location = new Location();
    try {

      LocationDoc = builder.parse(new FileInputStream("location.xml"));
      String ExtendedNameExpression = "/GeocodeResponse/result/formatted_address/text()";
      String LatitudeExpression = "/GeocodeResponse/result/geometry/location/lat/text()";
      String LongitudeExpression = "/GeocodeResponse/result/geometry/location/lng/text()";
      String ShortNameExpression = "/GeocodeResponse/result/address_component/short_name/text()";

      XPath xPath = XPathFactory.newInstance().newXPath();
      // read a string value
      location.setExtendedName(xPath.compile(ExtendedNameExpression).evaluate(LocationDoc));

      location.setLatitude(
          Float.parseFloat(xPath.compile(LatitudeExpression).evaluate(LocationDoc)));

      location.setLongitude(
          Float.parseFloat(xPath.compile(LongitudeExpression).evaluate(LocationDoc)));

      location.setName(xPath.compile(ShortNameExpression).evaluate(LocationDoc));

      // read an xml node using xpath

    } catch (Exception ex) {
      Logger.getLogger(DataFiller.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(location);
    return location;
  }
コード例 #20
0
ファイル: SimpleXMLElement.java プロジェクト: dlitz/resin
  /**
   * Runs an XPath expression on this node.
   *
   * @param env
   * @param expression
   * @return array of results
   * @throws XPathExpressionException
   */
  public Value xpath(Env env, String expression) {
    try {
      XPath xpath = XPathFactory.newInstance().newXPath();

      InputSource is = new InputSource(asXML(env).toInputStream());
      NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);

      int nodeLength = nodes.getLength();

      if (nodeLength == 0) return NullValue.NULL;

      // There are matching nodes
      ArrayValue result = new ArrayValueImpl();
      for (int i = 0; i < nodeLength; i++) {
        Node node = nodes.item(i);

        boolean isPrefix = node.getPrefix() != null;

        SimpleXMLElement xml =
            buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix);

        result.put(wrapJava(env, _cls, xml));
      }

      return result;
    } catch (XPathExpressionException e) {
      env.warning(e);
      log.log(Level.FINE, e.getMessage());

      return NullValue.NULL;
    }
  }
コード例 #21
0
 private Node[] merge(MergeHandler handler, List<Node> exhaustedNodes)
     throws XPathExpressionException, TransformerException {
   if (LOG.isDebugEnabled()) {
     LOG.debug("Processing handler: " + handler.getXPath());
   }
   if (handler.getChildren() != null) {
     MergeHandler[] children = handler.getChildren();
     for (int j = 0; j < children.length; j++) {
       Node[] temp = merge(children[j], exhaustedNodes);
       if (temp != null) {
         for (Node node : temp) {
           exhaustedNodes.add(node);
         }
       }
     }
   }
   NodeList nodeList1 =
       (NodeList) xPath.evaluate(handler.getXPath(), doc1, XPathConstants.NODESET);
   NodeList nodeList2 =
       (NodeList) xPath.evaluate(handler.getXPath(), doc2, XPathConstants.NODESET);
   if (nodeList1 != null && nodeList2 != null) {
     return handler.merge(nodeList1, nodeList2, exhaustedNodes);
   }
   return null;
 }
コード例 #22
0
  /**
   * Parses a single <code>&lt;result&gt;</code> entry from the Google Places XML response.
   *
   * @param resultNode
   * @return
   * @throws XPathExpressionException
   */
  private GooglePlace parseSingleResult(Node resultNode) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expr;
    GooglePlace place = new GooglePlace();

    if (resultNode != null) {
      expr = "name";
      place.setName((String) xpath.evaluate(expr, resultNode, XPathConstants.STRING));

      expr = "formatted_address";
      place.setFormattedAddress((String) xpath.evaluate(expr, resultNode, XPathConstants.STRING));

      expr = "geometry/location/lat";
      String lat = (String) xpath.evaluate(expr, resultNode, XPathConstants.STRING);
      if (lat != null && lat.length() > 0) {
        place.setLatitude(Double.parseDouble(lat));
      }

      expr = "geometry/location/lng";
      String lng = (String) xpath.evaluate(expr, resultNode, XPathConstants.STRING);
      if (lng != null && lng.length() > 0) {
        place.setLongitude(Double.parseDouble(lng));
      }
    }

    return place;
  }
 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);
 }
コード例 #24
0
ファイル: Demo.java プロジェクト: vijaykrsingh/Source_Code
  public static void readXpath()
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("D:\\temp\\test_2\\screen_2.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    // XPathExpression expr = xpath
    // .compile("//Screens/Screen[@number='1']/Button[@number='1']/Action[@type='onclick']/*");
    String xpathStr = "//Screen[@number='2007']/Button[@number='87'][@h='1']";
    XPathExpression expr = xpath.compile(xpathStr);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap nodeMap = nodes.item(i).getAttributes();
      String attrName = "";
      for (int j = 0; j < nodeMap.getLength(); j++) {
        attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("="));
        if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) {
          System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue());
        }
      }
    }
  }
コード例 #25
0
  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;
  }
コード例 #26
0
ファイル: JDKXPathAPI.java プロジェクト: Caltalys/docx4j
 /**
  * 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);
   }
 }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b())
            .goodB2G_source(request, response);

    final String xmldoc =
        "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";

    /* assume username||password as source */
    String[] tokens = data.split("||");
    if (tokens.length < 2) {
      return;
    }

    /* FIX: validate input using StringEscapeUtils */
    String uname = StringEscapeUtils.escapeXml(tokens[0]);
    String pword = StringEscapeUtils.escapeXml(tokens[1]);

    /* build xpath */
    XPath xp = XPathFactory.newInstance().newXPath();
    InputSource inxml = new InputSource(xmldoc);

    String query =
        "//users/user[name/text()='"
            + uname
            + "' and pass/text()='"
            + pword
            + "']"
            + "/secret/text()";
    String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
  }
コード例 #28
0
  @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.");
    }
  }
コード例 #29
0
  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));
      }
    }
  }
コード例 #30
0
  /**
   * Adds code for stylesheet parameters to wrapperDoc
   *
   * @param wrapperDoc DOM Document representing the UTF-X test definition file.
   * @param elem stylesheet-params element
   * @return void
   * @throws Exception
   */
  private void addStylesheetParams(Document wrapperDoc, Element elem) throws Exception {

    // find refElement (for insertBefore)
    Element xslOutputElement =
        (Element)
            xpath.evaluate("xsl:output", wrapperDoc.getDocumentElement(), XPathConstants.NODE);
    Node refNode = xslOutputElement.getNextSibling();

    NodeList params;
    try {
      params =
          (NodeList) xpath.evaluate("*[name() = 'utfx:with-param']", elem, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      throw new AssertionError(e);
    }

    for (int i = 0; i < params.getLength(); i++) {
      Element withParamElement = (Element) params.item(i);

      // create xsl:param element
      Element xslParam = wrapperDoc.createElementNS(UTFXNamespaceContext.XSL_NS_URI, "xsl:param");
      xslParam.setAttribute("name", withParamElement.getAttribute("name"));
      copySelectAttrOrChildNodes(withParamElement, wrapperDoc, xslParam);

      wrapperDoc.getDocumentElement().insertBefore(xslParam, refNode);
    }
  }