/**
   * 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);
    }
  }
コード例 #2
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));
      }
    }
  }
コード例 #3
0
ファイル: ModuleData.java プロジェクト: MaxDhn/gwt-test-utils
  private void initializeServlets(String moduleFilePath, Document document, XPath xpath)
      throws Exception {
    NodeList servlets =
        (NodeList) xpath.evaluate("/module/servlet", document, XPathConstants.NODESET);

    for (int i = 0; i < servlets.getLength(); i++) {
      Node servlet = servlets.item(i);
      String servletPath = xpath.evaluate("@path", servlet).trim();

      if (servletPath == null || "".equals(servletPath.trim())) {
        throw new GwtTestConfigurationException(
            "Error in file '"
                + moduleFilePath
                + "' : <servlet> declared without a correct 'path' value");
      }

      String servletClassName = xpath.evaluate("@class", servlet).trim();

      if (servletClassName == null || "".equals(servletClassName.trim())) {
        throw new GwtTestConfigurationException(
            "Error in file '"
                + moduleFilePath
                + "' : <servlet> declared without a correct 'class' value");
      }

      if (!servletPath.startsWith("/")) {
        servletPath = "/" + servletPath;
      }

      remoteServiceImpls.put(servletPath, servletClassName);
    }
  }
コード例 #4
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;
  }
コード例 #5
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;
  }
コード例 #6
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;
 }
コード例 #7
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();
    }
  }
コード例 #8
0
ファイル: selectNodeList.java プロジェクト: kmizu/spnuts
 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);
   }
 }
コード例 #9
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);
 }
コード例 #10
0
    @Test
    public void testRecursive2()
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
      final Document d =
          extractWadlAsDocument(
              target("/application.wadl")
                  .queryParam(WadlUtils.DETAILED_WADL_QUERY_PARAM, "true")
                  .request()
                  .get());

      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));
      String val =
          (String) xp.evaluate("/wadl:application/wadl:resources/@base", d, XPathConstants.STRING);
      assertEquals(val, getBaseUri().toString());
      // check only one resource with for 'root/loc'
      val = (String) xp.evaluate("count(//wadl:resource[@path='loc'])", d, XPathConstants.STRING);
      assertEquals("4", val);
      // check for method with id of hello
      val =
          (String)
              xp.evaluate(
                  "count(//wadl:resource[@path='loc']/wadl:method[@id='hello'])",
                  d,
                  XPathConstants.STRING);
      assertEquals("2", val);
    }
コード例 #11
0
    @Test
    @Ignore(
        "JERSEY-1670: WADL Options invoked on resources with same template returns only methods from one of them.")
    // TODO: fix
    public void testWadlForAmbiguousChildResourceTemplates()
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
      final Response response =
          target().path("resource/bar").request(MediaTypes.WADL_TYPE).options();

      final Document d = extractWadlAsDocument(response);
      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));

      String result =
          (String)
              xp.evaluate("//wadl:resource/wadl:method[@name='GET']/@id", d, XPathConstants.STRING);
      assertEquals("getTemplateA", result);

      result =
          (String)
              xp.evaluate(
                  "//wadl:resource/wadl:method[@name='POST']/@id", d, XPathConstants.STRING);
      assertEquals("postTemplateB", result);
    }
コード例 #12
0
ファイル: RunInfo.java プロジェクト: ronaldploeger/faban
    ConfigurationReader() throws Exception {
      configFileName = System.getProperty("benchmark.config");
      if (configFileName == null) {
        throw new IOException("Property \"benchmark.config\" not set.");
      }

      ParamReader reader = new ParamReader(configFileName, true);
      Document doc = reader.getDocument();
      xp = reader.getXPath();
      rootElement = doc.getDocumentElement();
      String rootNS = rootElement.getNamespaceURI();
      String rootName = rootElement.getLocalName();

      if (FABANURI.equals(rootNS) && "runConfig".equals(rootName)) {
        runConfigNode = rootElement;
      } else {
        runConfigNode = xp.evaluate("fa:runConfig", rootElement, XPathConstants.NODE);
      }
      if (runConfigNode == null) {
        throw new ConfigurationException("Cannot find <fa:runConfig> element.");
      }
      definingClassName = xp.evaluate("@definition", runConfigNode);

      // if the defining class is null, the benchmark definition needs
      // to be created based on the information in the driverConfig node.
      if (definingClassName == null || "".equals(definingClassName.trim())) {
        definingClassName = createDefinition(runConfigNode);
      }
    }
コード例 #13
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());
      }
    }
  }
コード例 #14
0
  @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);
    }
  }
コード例 #15
0
  private void load(InputStream is) throws IOException {
    Document doc = XmlUtils.parseInputStream(is);
    XPath xp = XmlUtils.createXPath();

    columns.clear();

    try {
      String firstLineHeaderStr = xp.evaluate("/AllColumns/@firstLineHeader", doc);
      if (firstLineHeaderStr != null && firstLineHeaderStr.equals("true")) {
        firstLineHeader = true;
      }

      NodeList nodes = (NodeList) xp.evaluate("/AllColumns/Column", doc, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {
        Element s = (Element) nodes.item(i);
        Column c = new Column();
        c.setName(s.getAttribute("name"));
        String type = s.getAttribute("type");
        if (type == null || type.isEmpty()) {
          type = FactorType.Unknown.toString();
        }
        c.setType(Column.FactorType.valueOf(type));
        String tmp = s.getAttribute("min");
        if (tmp.isEmpty() == false) {
          c.setMin(Double.valueOf(tmp));
        }
        tmp = s.getAttribute("max");
        if (tmp.isEmpty() == false) {
          c.setMax(Double.valueOf(tmp));
        }
        tmp = s.getAttribute("count");
        if (tmp.isEmpty() == false) {
          c.setCount(Long.valueOf(tmp));
        }
        tmp = s.getAttribute("sum");
        if (tmp.isEmpty() == false) {
          c.setSum(Double.valueOf(tmp));
        }
        tmp = s.getAttribute("quartile1");
        if (tmp.isEmpty() == false) {
          c.setQuartile1(Double.valueOf(tmp));
        }
        tmp = s.getAttribute("quartile2");
        if (tmp.isEmpty() == false) {
          c.setQuartile2(Double.valueOf(tmp));
        }
        tmp = s.getAttribute("quartile3");
        if (tmp.isEmpty() == false) {
          c.setQuartile3(Double.valueOf(tmp));
        }
        columns.add(c);
      }
    } catch (XPathExpressionException e) {
      throw new IOException("Error parsing XML", e);
    }
  }
コード例 #16
0
  @Test
  public void testProcess() throws XPathExpressionException, IOException {
    manualSAMLentry.setSamlAssertion(TestUtils.SAMPLE_SAML_1_ASSERTION);
    manualSAMLentry.process(secHeader, doc, contextMock);

    assertNotNull(xpath.evaluate("//saml1:Assertion", doc, XPathConstants.NODE));
    assertEquals(
        "1", xpath.evaluate("//saml1:Assertion/@MajorVersion", doc, XPathConstants.STRING));
    assertEquals(
        "1", xpath.evaluate("//saml1:Assertion/@MinorVersion", doc, XPathConstants.STRING));
  }
コード例 #17
0
ファイル: PlacesFile.java プロジェクト: edask/IMAPI
  public PlacesFile() throws ParserConfigurationException {

    // this.setErrorMessage(ApiConstants.IMAPISuccessCode, "");

    try {
      this.builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      this.document =
          builder.parse(ApiConfigClass.class.getResourceAsStream("/PlacesTranslation(TypeB).xml"));
      XPath xpath = XPathFactory.newInstance().newXPath();

      if (this.XpahthPlaces != null) {
        NodeList nodesDuch =
            (NodeList) xpath.evaluate(this.XpahthPlacesDutch, document, XPathConstants.NODESET);
        NodeList nodesEnglish =
            (NodeList) xpath.evaluate(this.XpahthPlacesEnglish, document, XPathConstants.NODESET);
        if (nodesDuch != null && nodesEnglish != null) {

          int howmanyNodes = nodesDuch.getLength();

          for (int i = 0; i < howmanyNodes; i++) {

            String Dutch = "", English = "";

            Node xNodeDuch = nodesDuch.item(i);
            Dutch = xNodeDuch.getNodeValue();

            Node xNodeEnglish = nodesEnglish.item(i);
            try {
              English = xNodeEnglish.getNodeValue();
            } catch (DOMException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            this.placesTrans.put(Dutch, English);
          }
        }
      }

    } catch (SAXException e) {
      String tempMsg = "SAXException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (IOException e) {
      String tempMsg = "IOException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #18
0
  protected void addServletTransportPorts(List<Integer> ports, String carbonXmlPath) {
    int port = 0;
    XPathFactory factory = XPathFactory.newInstance();
    NamespaceContext cntx = CarbonServer32Utils.getCarbonNamespace();
    File xmlDocument = new File(carbonXmlPath);
    try {
      InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document = builder.parse(xmlDocument);
      XPath xPath = factory.newXPath();
      xPath.setNamespaceContext(cntx);

      int offSet =
          Integer.parseInt(
              (String) xPath.evaluate("/Server/Ports/Offset", document, XPathConstants.STRING));
      String evaluate =
          (String)
              xPath.evaluate(
                  "/Server/Ports/ServletTransports/HTTPS", document, XPathConstants.STRING);

      if (!evaluate.equals("")) {
        port = Integer.parseInt(evaluate) + offSet;
      } else {
        port = getPortfromTransportXML("https");
      }
      ports.add(port);
      inputSource = new InputSource(new FileInputStream(xmlDocument));
      evaluate =
          (String)
              xPath.evaluate(
                  "/Server/Ports/ServletTransports/HTTP", document, XPathConstants.STRING);

      if (!evaluate.equals("")) {
        port = Integer.parseInt(evaluate) + offSet;
      } else {
        port = getPortfromTransportXML("http");
      }
      ports.add(port);

    } catch (NumberFormatException e) {
      log.error(e);
    } catch (FileNotFoundException e) {
      log.error(e);
    } catch (XPathExpressionException e) {
      log.error(e);
    } catch (ParserConfigurationException e) {
      log.error(e);
    } catch (SAXException e) {
      log.error(e);
    } catch (IOException e) {
      log.error(e);
    }
  }
コード例 #19
0
ファイル: XmlTools.java プロジェクト: styg/bumblebee-ETL
  public static String sumNodeValue(Document doc, String path) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(path, doc, XPathConstants.NODESET);

    long sum = 0L;
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      String value = (String) xpath.evaluate("text()", node, XPathConstants.STRING);
      sum += Long.parseLong(value);
    }

    return String.valueOf(sum);
  }
コード例 #20
0
ファイル: MetatypeTest.java プロジェクト: vikchilu/bnd
 static void assertAD(
     Document d,
     @SuppressWarnings("unused") String mname,
     String name,
     String id,
     String min,
     String max,
     String deflt,
     int cardinality,
     String type,
     String description,
     @SuppressWarnings("unused") String[] optionvalues,
     @SuppressWarnings("unused") String optionLabels[])
     throws XPathExpressionException {
   assertEquals(
       name, xpath.evaluate("//OCD/AD[@id='" + id + "']/@name", d, XPathConstants.STRING));
   assertEquals(id, xpath.evaluate("//OCD/AD[@id='" + id + "']/@id", d, XPathConstants.STRING));
   assertEquals(
       min == null ? "" : min,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@min", d, XPathConstants.STRING));
   assertEquals(
       max == null ? "" : max,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@max", d, XPathConstants.STRING));
   assertEquals(
       deflt == null ? "" : deflt,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@deflt", d, XPathConstants.STRING));
   assertEquals(
       cardinality + "",
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@cardinality", d, XPathConstants.STRING));
   assertEquals(
       type, xpath.evaluate("//OCD/AD[@id='" + id + "']/@type", d, XPathConstants.STRING));
   assertEquals(
       description == null ? "" : description,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@description", d, XPathConstants.STRING));
 }
コード例 #21
0
 /**
  * Update Status Monitor Parameter
  *
  * @param param parameter to replace
  * @throws XPathExpressionException
  */
 public void updateStatParameter(PhoneLabParameter param) throws XPathExpressionException {
   Element statusElement =
       (Element) xpath.evaluate("/manifest/statusmonitor", document, XPathConstants.NODE);
   Node pNode =
       (Node)
           xpath.evaluate(
               "parameter[@name='" + param.getName() + "']", statusElement, XPathConstants.NODE);
   statusElement.removeChild(pNode);
   Element newElement = document.createElement("parameter");
   if (param.getUnits() != null) newElement.setAttribute("units", param.getUnits());
   if (param.getValue() != null) newElement.setAttribute("value", param.getValue());
   if (param.getSetBy() != null) newElement.setAttribute("set_by", param.getSetBy());
   statusElement.appendChild(newElement);
 }
コード例 #22
0
ファイル: AuctionInfoType.java プロジェクト: kyeah/Donation-Z
  public AuctionInfoType(Node node) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Node childNode = null;
    NodeList nodeList = null;
    childNode = (Node) xpath.evaluate("BuyerID", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.BuyerID = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("ClosingDate", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.ClosingDate = childNode.getTextContent();
    }
  }
  /* 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);
  }
  /* 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);
  }
コード例 #25
0
ファイル: XmlHelper.java プロジェクト: MPDL-Collections/INGe
 public static Node xpathNode(String expr, Document doc) {
   try {
     return (Node) xpath.evaluate(expr, doc, XPathConstants.NODE);
   } catch (Exception e) {
     throw new RuntimeException("Cannot evaluate XPath:", e);
   }
 }
コード例 #26
0
ファイル: XmlHelper.java プロジェクト: MPDL-Collections/INGe
 public static Double xpathNumber(String expr, Document doc) {
   try {
     return (Double) xpath.evaluate(expr, doc, XPathConstants.NUMBER);
   } catch (Exception e) {
     throw new RuntimeException("Cannot evaluate XPath:", e);
   }
 }
コード例 #27
0
ファイル: XmlHelper.java プロジェクト: MPDL-Collections/INGe
 public static String xpathString(String expr, Document doc) {
   try {
     return (String) xpath.evaluate(expr, doc, XPathConstants.STRING);
   } catch (Exception e) {
     throw new RuntimeException("Cannot evaluate XPath:", e);
   }
 }
コード例 #28
0
ファイル: XPathTest.java プロジェクト: netroby/jdk9-dev
 /**
  * XPath.evaluate(java.lang.String expression, InputSource iSource, QName returnType) returns a
  * node value if returnType is Node.
  *
  * @throws Exception If any errors occur.
  */
 @Test
 public void testCheckXPath54() throws Exception {
   try (InputStream is = Files.newInputStream(XML_PATH)) {
     assertEquals(
         ((Attr) xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODE)).getValue(), "6");
   }
 }
コード例 #29
0
ファイル: XmlUtil.java プロジェクト: apixandru/monkeypatcher
 public static String evaluate(final Node element, final String xPath) {
   try {
     return XPATH.evaluate(xPath, element);
   } catch (XPathExpressionException e) {
     throw new IllegalArgumentException("XPath failure", e);
   }
 }
コード例 #30
0
ファイル: XmlUtil.java プロジェクト: apixandru/monkeypatcher
 private static NodeList getList(final Node element, final String xPath) {
   try {
     return (NodeList) XPATH.evaluate(xPath, element, XPathConstants.NODESET);
   } catch (XPathExpressionException e) {
     throw new IllegalArgumentException("XPath failure", e);
   }
 }