Ejemplo n.º 1
0
  public void c2() throws IOException, SAXException, ParserConfigurationException {

    // Si queremos usar el xml estatico-->
    // String inputFile = new String("forecast.xml");
    //

    // ListView<String> list = new ListView<String>();

    File outputFile = new File("xml.xml");

    String ciu = "q=Barcelona,es";
    URL xmlURL =
        new URL(
            "http://api.openweathermap.org/data/2.5/forecast/daily?"
                + ciu
                + "&units=metric&lang=sp&cnt=15&mode=xml&APPID=946990d16bf270450d5633215cff60ae");
    InputStream xml = xmlURL.openStream();

    // Protocolo de entrada
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    doc = db.parse(xml);
    doc.getDocumentElement().normalize();

    // normalizar

    NodeList sitio = doc.getElementsByTagName("location");
    Element ciutat = (Element) sitio.item(0);
    // System.out.println("La previson es de: " +
    // ciutat.getElementsByTagName("name").item(0).getTextContent());
    NodeList prev = doc.getElementsByTagName("time");
  }
Ejemplo n.º 2
0
  /**
   * Creates new org.w3c.dom.Document with Traversing possibility
   *
   * @param is <code>InputSource</code>
   * @return org.w3c.dom.Document
   * @throws CitationStyleManagerException
   */
  public static Document parseDocumentForTraversing(InputSource is)
      throws CitationStyleManagerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser;
    try {
      parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new CitationStyleManagerException("Cannot create DocumentBuilder:", e);
    }

    // Check for the traversal module
    DOMImplementation impl = parser.getDOMImplementation();
    if (!impl.hasFeature("traversal", "2.0")) {
      throw new CitationStyleManagerException(
          "A DOM implementation that supports traversal is required.");
    }
    Document doc;
    try {
      doc = parser.parse(is);
    } catch (Exception e) {
      throw new CitationStyleManagerException("Cannot parse InputSource to w3c document:", e);
    }

    return doc;
  }
Ejemplo n.º 3
0
  /**
   * Parses a given .svg for nodes
   *
   * @return <b>bothNodeLists</b> an Array with two NodeLists
   */
  public static NodeList[] parseSVG(Date date) {

    /* As it has to return two things, it can not return them
     * directly but has to encapsulate it in another object.
     */
    NodeList[] bothNodeLists = new NodeList[2];
    ;
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

      String SVGFileName = "./draw_map_svg.svg";
      File svgMap = new File(SVGFileName);

      System.out.println("Parsing the svg"); // Status message #1 Parsing
      System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing

      Document doc = docBuilder.parse(SVGFileName);

      // "text" is the actual planet/warplanet
      NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text");

      // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates.
      NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line");
      bothNodeLists[0] = listOfPlanetsAsXMLNode;
      bothNodeLists[1] = listOfLinesAsXMLNode;

      // normalize text representation
      doc.getDocumentElement().normalize();

      // Build the fileName the .svg should be renamed to, using the dateStringBuilder
      String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date);
      newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg");

      // Making sure the directory does exist, if not, it is created
      File svgdir = new File("svg");
      if (!svgdir.exists() || !svgdir.isDirectory()) {
        svgdir.mkdir();
      }

      svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName));

      System.out.println("Done parsing"); // Status message #3 Parsing

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    return bothNodeLists;
  }
Ejemplo n.º 4
0
  /**
   * Read parse trees from a Reader.
   *
   * @param filename
   * @param in The <code>Reader</code>
   * @param simplifiedTagset If `true`, convert part-of-speech labels to a simplified version of the
   *     EAGLES tagset, where the tags do not include extensive morphological analysis
   * @param aggressiveNormalization Perform aggressive "normalization" on the trees read from the
   *     provided corpus documents: split multi-word tokens into their constituent words (and infer
   *     parts of speech of the constituent words).
   * @param retainNER Retain NER information in preterminals (for later use in
   *     `MultiWordPreprocessor) and add NER-specific parents to single-word NE tokens
   * @param detailedAnnotations Retain detailed tree node annotations. These annotations on parse
   *     tree constituents may be useful for e.g. training a parser.
   */
  public SpanishXMLTreeReader(
      String filename,
      Reader in,
      boolean simplifiedTagset,
      boolean aggressiveNormalization,
      boolean retainNER,
      boolean detailedAnnotations) {
    TreebankLanguagePack tlp = new SpanishTreebankLanguagePack();

    this.simplifiedTagset = simplifiedTagset;
    this.detailedAnnotations = detailedAnnotations;

    stream = new ReaderInputStream(in, tlp.getEncoding());
    treeFactory = new LabeledScoredTreeFactory();
    treeNormalizer =
        new SpanishTreeNormalizer(simplifiedTagset, aggressiveNormalization, retainNER);

    DocumentBuilder parser = XMLUtils.getXmlParser();
    try {
      final Document xml = parser.parse(stream);
      final Element root = xml.getDocumentElement();
      sentences = root.getElementsByTagName(NODE_SENT);
      sentIdx = 0;

    } catch (SAXException e) {
      System.err.println("Parse exception while reading " + filename);
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 5
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());
      }
    }
  }
Ejemplo n.º 6
0
  public static void main(String[] args) {

    String outputDir = "./";

    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      if ("-o".equals(arg)) {
        outputDir = args[++i];
        continue;
      } else {
        System.out.println("XMLSchemaGenerator -o <path to newly created xsd schema file>");
        return;
      }
    }

    File f = new File(outputDir, "JGroups-" + Version.major + "." + Version.minor + ".xsd");
    try {
      FileWriter fw = new FileWriter(f, false);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();
      Document xmldoc = impl.createDocument("http://www.w3.org/2001/XMLSchema", "xs:schema", null);
      xmldoc.getDocumentElement().setAttribute("targetNamespace", "urn:org:jgroups");
      xmldoc.getDocumentElement().setAttribute("elementFormDefault", "qualified");

      Element xsElement = xmldoc.createElement("xs:element");
      xsElement.setAttribute("name", "config");
      xmldoc.getDocumentElement().appendChild(xsElement);

      Element complexType = xmldoc.createElement("xs:complexType");
      xsElement.appendChild(complexType);

      Element allType = xmldoc.createElement("xs:choice");
      allType.setAttribute("maxOccurs", "unbounded");
      complexType.appendChild(allType);

      Set<Class<?>> classes = getClasses("bboss.org.jgroups.protocols", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "");
      }
      classes = getClasses("bboss.org.jgroups.protocols.pbcast", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "pbcast.");
      }

      DOMSource domSource = new DOMSource(xmldoc);
      StreamResult streamResult = new StreamResult(fw);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
      serializer.transform(domSource, streamResult);

      fw.flush();
      fw.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
0
  /**
   * Reads the specified .machines file to get host names
   *
   * @param fileName
   * @throws IOException
   */
  private static void readEmulators(String fileName) throws IOException {
    try {
      FileInputStream is = new FileInputStream(fileName);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder parser = factory.newDocumentBuilder();

      Document d = parser.parse(is);

      Element e = d.getDocumentElement();

      NodeList n = e.getElementsByTagName("emul");

      // For every class
      String hostName = null;
      for (int i = 0; i < n.getLength(); i++) {
        Element x = (Element) n.item(i);

        hostName = x.getAttribute("hostname");
        emulators.add(hostName);
      }

      is.close();

    } catch (ParserConfigurationException pce) {
      log.error(pce.getMessage());

    } catch (SAXException se) {
      log.error(se.getMessage());
    }
  }
Ejemplo n.º 9
0
  public static AbstractPolicy getPolicy(String policy) {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    InputStream stream = null;
    // now use the factory to create the document builder
    try {
      builder = factory.newDocumentBuilder();
      stream = new ByteArrayInputStream(policy.getBytes("UTF-8"));
      Document doc = builder.parse(stream);
      Element root = doc.getDocumentElement();
      String name = root.getTagName();
      // see what type of policy this is
      if (name.equals("Policy")) {
        return Policy.getInstance(root);
      } else if (name.equals("PolicySet")) {
        return PolicySet.getInstance(root, null);
      } else {
        // this isn't a root type that we know how to handle
        throw new ParsingException("Unknown root document type: " + name);
      }
    } catch (Exception e) {
      throw new IllegalArgumentException("Error while parsing start up policy", e);
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          log.error("Error while closing input stream");
        }
      }
    }
  }
  /** Shows statistics of device if they are supported by the device */
  @Override
  @FXML
  public void handleStatistics(ActionEvent e) {
    String[] stats = new String[] {"", "U_", "M_"};
    try {
      ((RemoteOrderDisplay) service).retrieveStatistics(stats);
      DOMParser parser = new DOMParser();
      parser.parse(new InputSource(new java.io.StringReader(stats[1])));

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(stats[1].getBytes()));

      printStatistics(doc.getDocumentElement(), "");

      JOptionPane.showMessageDialog(
          null, statistics, "Statistics", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, ioe.getMessage());
      ioe.printStackTrace();
    } catch (SAXException saxe) {
      JOptionPane.showMessageDialog(null, saxe.getMessage());
      saxe.printStackTrace();
    } catch (ParserConfigurationException e1) {
      JOptionPane.showMessageDialog(null, e1.getMessage());
      e1.printStackTrace();
    } catch (JposException jpe) {
      jpe.printStackTrace();
      JOptionPane.showMessageDialog(
          null, "Statistics are not supported!", "Statistics", JOptionPane.ERROR_MESSAGE);
    }

    statistics = "";
  }
  public void parse(FullBuildModel model, File projectPath, String fileName, String[] sourcePaths)
      throws IOException {
    logger.info("Starting Gendarme parsing");

    this.projectPath = projectPath;
    this.model = model;
    this.reportParentFile = new File(fileName).getParentFile();
    this.sourcePaths = sourcePaths;

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
      docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new FileInputStream(new File(projectPath, fileName)));

      NodeList mainNode = doc.getElementsByTagName("gendarme-output");

      Element rootElement = (Element) mainNode.item(0);
      Element resultsElement = (Element) rootElement.getElementsByTagName("results").item(0);
      Element rulesElement = (Element) rootElement.getElementsByTagName("rules").item(0);

      // load all rules into the cache
      parseRules(XmlElementUtil.getNamedChildElements(rulesElement, "rule"));

      // parse each violations
      parseViolations(XmlElementUtil.getNamedChildElements(resultsElement, "rule"));

    } catch (ParserConfigurationException pce) {
      throw new IOException(pce);
    } catch (SAXException se) {
      throw new IOException(se);
    }
  }
Ejemplo n.º 12
0
  public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    DocumentBuilder parser = null;

    try {
      parser = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
      throw new IOException(ex.getLocalizedMessage());
    } finally {
      // Note: Above code is OK since clients are responsible to close the stream
    }
    parser.setErrorHandler(new DefaultHandler());
    Element xmlJarDesc = parser.parse(new InputSource(fInputStream)).getDocumentElement();
    if (!xmlJarDesc.getNodeName().equals(JarPackagerUtil.DESCRIPTION_EXTENSION)) {
      throw new IOException(JarPackagerMessages.JarPackageReader_error_badFormat);
    }
    NodeList topLevelElements = xmlJarDesc.getChildNodes();
    for (int i = 0; i < topLevelElements.getLength(); i++) {
      Node node = topLevelElements.item(i);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;
      Element element = (Element) node;
      xmlReadJarLocation(jarPackage, element);
      xmlReadOptions(jarPackage, element);
      xmlReadRefactoring(jarPackage, element);
      xmlReadSelectedProjects(jarPackage, element);
      if (jarPackage.areGeneratedFilesExported()) xmlReadManifest(jarPackage, element);
      xmlReadSelectedElements(jarPackage, element);
    }
    return jarPackage;
  }
  /**
   * Parse the specified source and produce a {@link Document}.
   *
   * @param source The source.
   * @return The {@link Document}.
   */
  public static Document parse(InputSource source) {
    DocumentBuilder docBuilder;

    try {
      docBuilder = _docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw TransformMessages.MESSAGES.unexpectedDOMParserConfigException(e);
    }

    try {
      return docBuilder.parse(source);
    } catch (SAXException e) {
      throw TransformMessages.MESSAGES.errorReadingDOMSourceSAX(e);
    } catch (IOException e) {
      throw TransformMessages.MESSAGES.errorReadingDOMSourceIO(e);
    } finally {
      InputStream stream = source.getByteStream();
      Reader reader = source.getCharacterStream();
      try {
        try {
          if (stream != null) {
            stream.close();
          }
        } finally {
          if (reader != null) {
            reader.close();
          }
        }
      } catch (IOException e) {
        TransformLogger.ROOT_LOGGER.exceptionClosingDOMInputSource(e.getMessage());
      }
    }
  }
Ejemplo n.º 14
0
  public Document getDocument(
      double fromLatitude, double fromLongitude, GeoPoint toPosition, String mode)
      throws Exception {
    String url =
        "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin="
            + fromLatitude
            + ","
            + fromLongitude
            + "&destination="
            + toPosition.lat
            + ","
            + toPosition.lng
            + "&sensor=false&units=metric&mode="
            + mode;

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); // 20seconds
    HttpConnectionParams.setSoTimeout(httpParameters, 20000); // 20 seconds

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    HttpContext localContext = new BasicHttpContext();

    HttpResponse response = httpClient.execute(httpPost, localContext);

    InputStream in = response.getEntity().getContent();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(in);
    return doc;
  }
Ejemplo n.º 15
0
  public AbstractActor readActor(String path) {
    try {
      File fXmlFile = new File(path);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      String topTag = doc.getDocumentElement().getNodeName();
      AbstractActor result;

      if (topTag.equals("Actor")) {
        result = createActor(doc.getDocumentElement());
      } else if (topTag.equals("Network")) {
        result = createNetwork(doc.getDocumentElement());
      } else if (topTag.equals("ExternalActor")) {
        result = createExternalActor(doc.getDocumentElement());
      } else {
        throw new RuntimeException("Invalid top tag in XML ir document");
      }

      // As a last step, patch the forward declarations
      for (ForwardDeclaration decl : forwardDeclarationMap.keySet()) {
        decl.setDeclaration((Declaration) findIrObject(forwardDeclarationMap.get(decl)));
      }

      return result;
    } catch (Exception x) {
      System.err.println("[ActorDirectory]ÊError reading '" + path + "' x " + x.getMessage());
      return null;
    }
  }
  public void run() {
    /*
    	Pre-conditions: p and game have been instantiated.

    	Post-conditions:
    		There will no longer be a connection to the player
    		and the player can be removed from the game.

    	Semantics:
    		This method will loop while listening for messages
    		and moves from p. When the connection to the player
    		is lost this method will inform the game and stop
    		looping.

    */
    try {
      while ((message = p.getInput().readLine()) != null) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(message));
        Document doc = builder.parse(is);

        Element root = doc.getDocumentElement();

        // Server only deals with messages
        if (root.getTagName().equals("message")) {
          parseMessage(root);
        }
      }
    } catch (Exception e) {
    }

    game.removePlayer(p);
  }
Ejemplo n.º 17
0
  public Namespace readNamespace(String path) {
    try {
      File fXmlFile = new File(path);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      String topTag = doc.getDocumentElement().getNodeName();

      if (topTag.equals("Namespace")) {
        Namespace result = createNamespace(doc.getDocumentElement());
        for (ForwardDeclaration decl : forwardDeclarationMap.keySet()) {
          decl.setDeclaration((Declaration) findIrObject(forwardDeclarationMap.get(decl)));
        }
        return result;
      } else {
        throw new RuntimeException("Invalid top tag in XML ir document");
      }

      // As a last step, patch the forward declarations

    } catch (Exception e) {
      System.err.println("[IrXmlReader. Error reading '" + path + "' message = " + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 18
0
  /**
   * Description of fromFile()
   *
   * @param file
   */
  public void fromFile(String file) {

    // overwrite whatever was in the data structure
    this.urls = null;

    File fXmlFile = new File(file);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
      dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);

      doc.getDocumentElement().normalize();
      org.w3c.dom.Element docElement = doc.getDocumentElement();

      this.readHelper(docElement);

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 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);
 }
Ejemplo n.º 20
0
 /**
  * load.
  *
  * @param resource a {@link org.springframework.core.io.Resource} object.
  * @return a {@link java.util.List} object.
  */
 public List<ReconfigBeanDefinitionHolder> load(Resource resource) {
   List<ReconfigBeanDefinitionHolder> holders = new ArrayList<ReconfigBeanDefinitionHolder>();
   try {
     InputStream inputStream = resource.getInputStream();
     try {
       InputSource inputSource = new InputSource(inputStream);
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder docBuilder = factory.newDocumentBuilder();
       Document doc = docBuilder.parse(inputSource);
       Element root = doc.getDocumentElement();
       NodeList nl = root.getChildNodes();
       BeanDefinitionParser parser = new BeanDefinitionParser();
       for (int i = 0; i < nl.getLength(); i++) {
         Node node = nl.item(i);
         if (node instanceof Element) {
           Element ele = (Element) node;
           ReconfigBeanDefinitionHolder holder = parser.parseBeanDefinitionElement(ele);
           holders.add(holder);
         }
       }
     } finally {
       if (null != inputStream) {
         inputStream.close();
       }
     }
   } catch (Exception ex) {
     throw new RuntimeException(
         "IOException parsing XML document from " + resource.getDescription(), ex);
   }
   return holders;
 }
Ejemplo n.º 21
0
 /**
  * Get value out of a specified element's name in XML file
  *
  * @param xmlFile XML File to look at
  * @param elementName Element name, in which the value is wanted
  * @return (String) Element's value
  * @throws IOException
  */
 public static String parseXmlFile(String xmlFile, String elementName) throws IOException {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   String output = null;
   try {
     File file = new File(xmlFile);
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(file);
     doc.getDocumentElement().normalize();
     NodeList nodeLst = doc.getDocumentElement().getElementsByTagName("key");
     for (int i = 0; i < nodeLst.getLength(); i++) {
       Node currentNode = nodeLst.item(i);
       Element currentElement = (Element) currentNode;
       String keyName = currentElement.getAttribute("name");
       if (!keyName.equals(elementName)) {
         continue;
       } else {
         Element value = (Element) currentElement.getElementsByTagName("value").item(0);
         output = value.getChildNodes().item(0).getNodeValue();
         break;
       }
     }
   } catch (ParserConfigurationException pce) {
     logger.warn(pce);
   } catch (SAXException se) {
     logger.warn(se);
   }
   return output;
 }
Ejemplo n.º 22
0
 public BMCreateButtonResponseType(Object xmlSoap)
     throws IOException, SAXException, ParserConfigurationException {
   super(xmlSoap);
   DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = builderFactory.newDocumentBuilder();
   InputSource inStream = new InputSource();
   inStream.setCharacterStream(new StringReader((String) xmlSoap));
   Document document = builder.parse(inStream);
   NodeList nodeList = null;
   String xmlString = "";
   if (document.getElementsByTagName("Website").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Website").item(0))) {
       this.Website = (String) document.getElementsByTagName("Website").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("Email").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Email").item(0))) {
       this.Email = (String) document.getElementsByTagName("Email").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("Mobile").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Mobile").item(0))) {
       this.Mobile = (String) document.getElementsByTagName("Mobile").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("HostedButtonID").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("HostedButtonID").item(0))) {
       this.HostedButtonID =
           (String) document.getElementsByTagName("HostedButtonID").item(0).getTextContent();
     }
   }
 }
 /** get all the categories of all tv programs */
 public static ArrayList<OnlineVideo> getAllCategory(final Context context) {
   ArrayList<OnlineVideo> result = new ArrayList<OnlineVideo>();
   DocumentBuilderFactory docBuilderFactory = null;
   DocumentBuilder docBuilder = null;
   Document doc = null;
   try {
     docBuilderFactory = DocumentBuilderFactory.newInstance();
     docBuilder = docBuilderFactory.newDocumentBuilder();
     // xml file is set in 'assets' folder
     doc = docBuilder.parse(context.getResources().getAssets().open("online.xml"));
     // root element
     Element root = doc.getDocumentElement();
     NodeList nodeList = root.getElementsByTagName("category");
     for (int i = 0; i < nodeList.getLength(); i++) {
       Node node = nodeList.item(i); // category
       OnlineVideo ov = new OnlineVideo();
       NamedNodeMap attr = node.getAttributes();
       ov.title = attr.getNamedItem("name").getNodeValue();
       ov.id = attr.getNamedItem("id").getNodeValue();
       ov.category = 1;
       ov.level = 2;
       ov.is_category = true;
       result.add(ov);
       // Read Node
     }
   } catch (IOException e) {
   } catch (SAXException e) {
   } catch (ParserConfigurationException e) {
   } finally {
     doc = null;
     docBuilder = null;
     docBuilderFactory = null;
   }
   return result;
 }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
Ejemplo n.º 25
0
  @Before
  public void dbInit() throws Exception {
    String configFileName = System.getProperty("user.home");
    if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
      configFileName += "/.pokerth/config.xml";
    } else {
      configFileName += "/AppData/Roaming/pokerth/config.xml";
    }
    File file = new File(configFileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0);

    Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0);
    String dbAddress = dbAddressNode.getAttribute("value");

    Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0);
    String dbUser = dbUserNode.getAttribute("value");

    Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0);
    String dbPassword = dbPasswordNode.getAttribute("value");

    Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0);
    String dbName = dbNameNode.getAttribute("value");

    final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  }
 public void setUp() throws ParserConfigurationException {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   factory.setNamespaceAware(true);
   DocumentBuilder builder = factory.newDocumentBuilder();
   doc = builder.newDocument();
   doc.appendChild(doc.createElement("root"));
 }
Ejemplo n.º 27
0
  private void loadExcludes() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputStream is = null;

    if (excludesFile == null) {
      is = config.getServletContext().getResourceAsStream(excludesFileName);
    } else if (excludesFile.exists() && excludesFile.canRead()) {
      is = excludesFile.toURI().toURL().openStream();
    }

    if (is == null) {
      throw new IllegalStateException(
          "Cannot load excludes configuration file \""
              + excludesFileName
              + "\" as specified in \"sitemesh.xml\" or \"sitemesh-default.xml\"");
    }

    Document document = builder.parse(is);
    Element root = document.getDocumentElement();
    NodeList sections = root.getChildNodes();

    // Loop through child elements of root node looking for the <excludes> block
    for (int i = 0; i < sections.getLength(); i++) {
      if (sections.item(i) instanceof Element) {
        Element curr = (Element) sections.item(i);
        if ("excludes".equalsIgnoreCase(curr.getTagName())) {
          loadExcludeUrls(curr.getChildNodes());
        }
      }
    }
  }
Ejemplo n.º 28
0
  public static String RecogniseFromXml(byte[] bin) {

    String tranCode = "";
    String xmlStr = new String(bin);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Element theTranCode = null, root = null;
    try {
      factory.setIgnoringElementContentWhitespace(true);

      DocumentBuilder db = factory.newDocumentBuilder();

      final byte[] bytes = xmlStr.getBytes();
      final ByteArrayInputStream is = new ByteArrayInputStream(bytes);
      final InputSource source = new InputSource(is);

      Document xmldoc = db.parse(source);
      root = xmldoc.getDocumentElement();
      theTranCode = (Element) selectSingleNode("/root/head/transid", root);
      // Element nameNode = (Element) theTranCode.getElementsByTagName("price").item(0);
      if (theTranCode != null) {
        tranCode = theTranCode.getFirstChild().getNodeValue();
      } else {
        System.out.println("获取 /root/head/transid 失败!");
      }
      // System.out.println(tranCode);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return tranCode;
  }
Ejemplo n.º 29
0
  /**
   * Get root element from XML String
   *
   * @param arg XML String
   * @return Root Element
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public static Element getDocumentElementFromString(String arg)
      throws ParserConfigurationException, SAXException, IOException {

    System.out.println("1 - before: " + arg);

    String xml = arg.trim().replaceFirst("^([\\W]+)<", "<");

    DocumentBuilderFactory dbf;
    System.out.println("2 - after: " + xml);
    DocumentBuilder db;
    System.out.println("3");
    Document document;
    System.out.println("4");
    dbf = DocumentBuilderFactory.newInstance();
    System.out.println("5");
    db = dbf.newDocumentBuilder();
    System.out.println("6");
    document = db.parse(new InputSource(new StringReader(xml)));
    System.out.println("7");
    Element element = document.getDocumentElement();
    System.out.println("8");

    db = null;
    dbf = null;
    document = null;

    return element;
  }
Ejemplo n.º 30
0
  /**
   * Parses the XML stored in the given file and returns a Document object that represents the
   * parsed XML file
   *
   * @param xml
   * @return
   */
  public static Document parseXML(File file) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {

      // Using factory get an instance of document builder
      DocumentBuilder db = dbf.newDocumentBuilder();

      // parse using builder to get DOM representation of the XML file
      FileInputStream fis = new FileInputStream(file);
      Document domDoc = db.parse(fis);
      domDoc.normalize();
      fis.close();

      return domDoc;

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      System.err.println("File not found: " + e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
    }

    // default for exceptions
    return null;
  }