Пример #1
0
  protected List<String> getHiddenAttributeNames() {
    ArrayList<String> hiddenAttributeNames = null;

    try {
      InputStream resource = getClass().getClassLoader().getResourceAsStream("amConsoleConfig.xml");
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(resource);
      NodeList nodes =
          (NodeList)
              XPathFactory.newInstance()
                  .newXPath()
                  .evaluate(
                      "//consoleconfig/servicesconfig/consoleservice/@realmEnableHideAttrName",
                      doc,
                      XPathConstants.NODESET);
      String rawList = nodes.item(0).getNodeValue();
      hiddenAttributeNames = new ArrayList<String>(Arrays.asList(rawList.split(" ")));
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return hiddenAttributeNames;
  }
 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);
 }
Пример #3
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;
  }
Пример #4
0
  /**
   * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter
   * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second
   * string parameter The return value is of type string e.g. this is currently used primarily for
   * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag
   */
  private String xpathlookup(String xml, String expression) {

    try {

      // Parse the XML as a W3C document.
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document =
          builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml));

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

      String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING);

      return rv;

    } catch (ParserConfigurationException e) {
      System.err.println("ParserConfigurationException caught...");
      e.printStackTrace();
      return null;
    } catch (XPathExpressionException e) {
      System.err.println("XPathExpressionException caught...");
      e.printStackTrace();
      return null;
    } catch (SAXException e) {
      System.err.println("SAXException caught...");
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      System.err.println("IOException caught...");
      e.printStackTrace();
      return null;
    }
  }
  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();
    }
  }
Пример #6
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;
  }
Пример #7
0
  /**
   * Метод получения предложений на текущем языке
   *
   * @param id код предложения
   * @return строка предложения
   */
  public static String get(String id) {
    try {

      // узел с определенным id
      Node sentenceNode =
          (Node)
              xPathDictionary.evaluate("id('" + id + "')", documentDictionary, XPathConstants.NODE);

      // получение предложения на текущем языке
      NodeList list = sentenceNode.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        Node currentNode = list.item(i);
        if (language.equals(currentNode.getNodeName())) {
          return currentNode.getChildNodes().item(0).getNodeValue();
        }
      }

    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(0);
    }

    // возвращаем пустую строку, если произошла ошибка
    return "";
  }
Пример #8
0
    @Override
    public void run() {
      final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      final XPath xPath = XPathFactory.newInstance().newXPath();
      final String expression = "//" + TAG_TRACK_POINT;
      final String speedExpression = "//" + TAG_SPEED;

      NodeList nodeList = null;
      NodeList speedList = null;
      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(traceFile);
        nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        speedList =
            (NodeList) xPath.compile(speedExpression).evaluate(document, XPathConstants.NODESET);
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
      } catch (SAXException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (XPathExpressionException e) {
        e.printStackTrace();
      }

      parse(nodeList, speedList);
    }
 /**
  * Update an application in the manifest
  *
  * @param app app to replace for
  */
 public void updateApplication(PhoneLabApplication app) {
   try {
     Node node =
         (Node)
             xpath.evaluate(
                 "/manifest/statusmonitor/parameter[@package_name='" + app.getPackageName() + "']",
                 document,
                 XPathConstants.NODE);
     if (node != null) { // exist
       Node parentNode = node.getParentNode();
       parentNode.removeChild(node);
       Element newElement = document.createElement("application");
       if (app.getPackageName() != null)
         newElement.setAttribute("package_name", app.getPackageName());
       if (app.getName() != null) newElement.setAttribute("name", app.getName());
       if (app.getDescription() != null)
         newElement.setAttribute("description", app.getDescription());
       if (app.getType() != null) newElement.setAttribute("type", app.getType());
       if (app.getStartTime() != null) newElement.setAttribute("start_time", app.getStartTime());
       if (app.getEndTime() != null) newElement.setAttribute("end_time", app.getEndTime());
       if (app.getDownload() != null) newElement.setAttribute("download", app.getDownload());
       if (app.getVersion() != null) newElement.setAttribute("version", app.getVersion());
       if (app.getAction() != null) newElement.setAttribute("action", app.getAction());
       document.getFirstChild().appendChild(newElement);
     }
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
 }
Пример #10
0
    @Override
    protected String doInBackground(String... strings) {
      TelephonyManager telephonyManager =
          (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      try {
        String query =
            SoapRequest1.sendCheckList(
                telephonyManager.getDeviceId(),
                estaciones.get(station.getSelectedItemPosition()).getId(),
                modulos,
                imagenes);

        ArrayList<String> response = XMLParser.getReturnCode2(query);

        ok = response.get(0).equals("0");
        if (ok) return query;
        else return response.get(1);

      } catch (SAXException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (XPathExpressionException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (IOException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (Exception e) {
        e.printStackTrace();
        return "Ha ocurrido un error";
      }
    }
Пример #11
0
    @Override
    protected String doInBackground(String... strings) {
      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String query = SoapRequest1.getDepartament(telephonyManager.getDeviceId());
        ArrayList<String> parse = XMLParser.getReturnCode2(query);
        Log.d("ELEMENTS", query);
        if (parse.get(0).equals("0")) {
          state = true;
          return query;
        } else return parse.get(1);

      } catch (IOException e) {
        e.printStackTrace();
        return "No se pudo conectar con el servidor, compruebe se conexión a internet y reintente";
      } catch (SAXException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (XPathExpressionException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (Exception e) {
        e.printStackTrace();
        return "Ha ocurrido un error, por favor reintente";
      }
    }
  // read data from the starting XML file (people.xml)
  // and put them into a PeopleStore instance
  public static void initializeDB() {
    HealthProfileReader HP = new HealthProfileReader();
    List<String> peopleInfo = null;
    try {
      peopleInfo = HP.readallinfo();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    // "saves" all the retrieved information about people
    for (int i = 0; i < peopleInfo.size(); i += 8) {
      Person pallino =
          new Person(
              peopleInfo.get(i + 0), // id
              peopleInfo.get(i + 1), // firstname
              peopleInfo.get(i + 2), // lastname
              peopleInfo.get(i + 3)); // birthdate

      pallino.setHProfile(
          new HealthProfile(
              peopleInfo.get(i + 4), // last update
              Double.parseDouble(peopleInfo.get(i + 5)), // weight
              Double.parseDouble(peopleInfo.get(i + 6)))); // height
      // bmi will be calculated in HealthProfile

      people.getData().add(pallino);
    }
  }
Пример #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 String getStr(String path) {
   try {
     if (!"".equals(root) && root != null) path = root + "/" + path;
     return pather.evaluate(path, doc);
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return "";
 }
Пример #15
0
 public String getAttr(String path, String attrName) {
   if (!"".equals(root) && root != null) path = root + "/" + path;
   try {
     return pather.evaluate(
         new StringBuilder().append(path).append("/@").append(attrName).toString(), doc);
   } catch (XPathExpressionException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   }
   return "";
 }
 public LFParseEnricher() {
   XPathFactory factory = XPathFactory.newInstance();
   xpath = factory.newXPath();
   try {
     theoryXPath = xpath.compile("//theory");
     viewXPath = xpath.compile("//view");
     viewXPath = xpath.compile("//include");
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Пример #17
0
  public static Node selectSingleNode(String express, Object source) { // 查找节点,并返回第一个符合条件节点
    Node result = null;
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    try {
      result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return result;
  }
Пример #18
0
  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();
    }
  }
Пример #19
0
 public static String retrieveXPathAsString(XPathExpression expression, Document doc) {
   Object result;
   try {
     result = expression.evaluate(doc, XPathConstants.NODE);
     if (result != null && result instanceof Node) {
       Node node = (Node) result;
       return node.getTextContent();
     }
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return null;
 }
Пример #20
0
  /**
   * @param deviceDef
   * @param maxAge
   * @param vendorFirmware
   * @param discoveryUSN
   * @param discoveryUDN
   * @return a new {@link RootDevice}, or <code>null</code>
   */
  public static RootDevice build(
      String myIP,
      URL deviceDef,
      String maxAge,
      String vendorFirmware,
      String discoveryUSN,
      String discoveryUDN) {
    Document xml = XMLUtil.getXML(deviceDef);

    URL baseURL = null;

    try {
      String base = XMLUtil.xpath.evaluate("/root/URLBase", xml);

      try {
        if (base != null && base.trim().length() > 0) {
          baseURL = new URL(base);
        }
      } catch (MalformedURLException malformedEx) {
        // crappy urlbase provided
        // log.warn( "Error occured during device baseURL " + base
        // + " parsing, building it from device default location",
        // malformedEx );
        malformedEx.printStackTrace();
      }

      if (baseURL == null) {
        String URL =
            deviceDef.getProtocol() + "://" + deviceDef.getHost() + ":" + deviceDef.getPort();
        String path = deviceDef.getPath();
        if (path != null) {
          int lastSlash = path.lastIndexOf('/');
          if (lastSlash != -1) {
            URL += path.substring(0, lastSlash);
          }
        }
        try {
          baseURL = new URL(URL);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
      }

      return new RootDevice(
          myIP, xml, baseURL, maxAge, deviceDef, vendorFirmware, discoveryUSN, discoveryUDN);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return null;
  }
Пример #21
0
 public String getStat(String playerId, String item) {
   String query = String.format(QUERY_TEMPLATE, playerId, item);
   String result = null;
   // XPath
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   try {
     XPathExpression exp = xpath.compile(query);
     result = (String) exp.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return result;
 }
Пример #22
0
 public int getNodeCount(String path) {
   try {
     if (!"".equals(root) && root != null) path = root + "/" + path;
     return ((Number)
             pather.evaluate(
                 new StringBuilder().append("count(").append(path).append(")").toString(),
                 doc,
                 XPathConstants.NUMBER))
         .intValue();
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return -1;
 }
Пример #23
0
  public boolean loadKnowledge(Knowledge original, Document doc, boolean allowOverrides)
      throws MAtmosException {
    try {
      parseXML(original, doc, allowOverrides);
      return true;
    } catch (XPathExpressionException e) {
      e.printStackTrace();
      return false;

    } catch (NumberFormatException e) {
      e.printStackTrace();
      return false;
    }
  }
  public NodeList getChildrenByTag(Element e, String tag) {

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

    try {
      return (NodeList) xpath.evaluate("./" + tag, e, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
      // TODO Auto-generated catch block
      ex.printStackTrace();
    }

    return null;
  }
  public NodeList getVerbs(Element e) {
    // return e.getElementsByTagName("verb");

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

    try {
      return (NodeList) xpath.evaluate("./verb", e, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
      // TODO Auto-generated catch block
      ex.printStackTrace();
    }

    return null;
  }
Пример #26
0
  /** метод для инициализирования */
  public static void init() {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();

    // получаем конфигурационный документ
    Document document = getDocument(xmlConfigPath);
    try {

      // устанавливаем путь до файла со списком задач
      xmlTodoListPath = xPath.evaluate("config/todo-list-path", document);

      // устанавливаем текущий язык
      language = xPath.evaluate("config/current-language", document);

      // получаем список доступных языков
      NodeList languagesNL =
          (NodeList)
              (xPath.evaluate("config/languages/language", document, XPathConstants.NODESET));
      languages = new String[languagesNL.getLength()];
      for (int i = 0; i < languagesNL.getLength(); i++) {
        languages[i] = languagesNL.item(i).getTextContent();
      }

      // получаем список категории
      categories = new ArrayList<>();
      NodeList categoriesNL =
          (NodeList)
              (xPath.evaluate("config/todo-categories/category", document, XPathConstants.NODESET));
      for (int i = 0; i < categoriesNL.getLength(); i++) {

        String title = xPath.evaluate("title", categoriesNL.item(i));
        String icon = xPath.evaluate("icon", categoriesNL.item(i));
        int background = Integer.parseInt(xPath.evaluate("background", categoriesNL.item(i)), 16);
        categories.add(new Category(title, icon, background));
      }

    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(0);
    }

    // dictionary
    documentDictionary = getDocument(xmlDictionaryPath);
    XPathFactory xPathFactoryDictionary = XPathFactory.newInstance();
    xPathDictionary = xPathFactoryDictionary.newXPath();
  }
Пример #27
0
  public ForecastDay(XPath xpath, Node node) {
    try {
      this.title = (String) xpath.evaluate("./aws:title", node, XPathConstants.STRING);
      this.altTitle =
          (((Node) xpath.evaluate("./aws:title", node, XPathConstants.NODE))
              .getAttributes()
              .getNamedItem("alttitle")
              .getNodeValue());
      this.description = (String) xpath.evaluate("./aws:description", node, XPathConstants.STRING);
      this.shortPrediction =
          (String) xpath.evaluate("./aws:short-prediction", node, XPathConstants.STRING);
      this.imageURL = (String) xpath.evaluate("./aws:image", node, XPathConstants.STRING);
      this.iconName =
          (((Node) xpath.evaluate("./aws:image", node, XPathConstants.NODE))
              .getAttributes()
              .getNamedItem("icon")
              .getNodeValue());
      this.isNight =
          ((Node) xpath.evaluate("./aws:title", node, XPathConstants.NODE))
              .getAttributes()
              .getNamedItem("alttitle")
              .getNodeValue()
              .equals("1");
      this.longPrediction =
          (String) xpath.evaluate("./aws:prediction", node, XPathConstants.STRING);
      this.highTemp = (String) xpath.evaluate("./aws:high", node, XPathConstants.STRING);
      this.highTempUnits =
          (String)
              (((Node) xpath.evaluate("./aws:high", node, XPathConstants.NODE))
                  .getAttributes()
                  .getNamedItem("units")
                  .getNodeValue());
      this.lowTemp = (String) xpath.evaluate("./aws:low", node, XPathConstants.STRING);
      this.lowTempUnits =
          (String)
              (((Node) xpath.evaluate("./aws:low", node, XPathConstants.NODE))
                  .getAttributes()
                  .getNamedItem("units")
                  .getNodeValue());

    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #28
0
  private NodeList evaluateExpr(String response, String expression) {
    // This code uses the XPath support built into JAXP.
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = null;

    try {
      nodeList =
          (NodeList)
              xpath.evaluate(
                  expression,
                  new InputSource(new StringReader(response.toString())),
                  XPathConstants.NODESET);
    } catch (XPathExpressionException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    return nodeList;
  }
Пример #29
0
  public double measureMetric(Document document) {
    double count = 0;

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

    try {
      XPathExpression expression = xpath.compile(XPATH_QUERY);
      count = (Double) expression.evaluate(document, XPathConstants.NUMBER);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return count;

    // Para retornar so 0 ou 1 usar o seguinte:
    // return (count > 0.0) ? 1.0 : 0.0;
  }
Пример #30
0
 private static Emailer parseEmailer(InputSource inputSource) {
   try {
     String smtp =
         (String) xpath.evaluate("/testharness/emailer/@smtp", inputSource, XPathConstants.STRING);
     String from =
         (String) xpath.evaluate("/testharness/emailer/@from", inputSource, XPathConstants.STRING);
     List<String> recipients = new ArrayList<String>();
     NodeList nodes =
         (NodeList)
             xpath.evaluate("/testharness/emailer/recipient", inputSource, XPathConstants.NODESET);
     for (int i = 0; i < nodes.getLength(); i++) {
       recipients.add(nodes.item(i).getTextContent());
     }
     return new Emailer(smtp, recipients, from);
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return null;
 }