Ejemplo n.º 1
0
  private XFacetedQuery XML2Query(Document doc) {
    try {
      Node node = null;
      NamedNodeMap map = null;

      node = doc.getElementsByTagName("action").item(0);
      map = node.getAttributes();

      // create XFacetedQuery
      node = doc.getElementsByTagName("targetNode").item(0);
      map = node.getAttributes();
      int target = new Integer(map.getNamedItem("index").getNodeValue()).intValue();

      CatRelGraph graph = schemaFactory.createCatRelGraph();
      node = doc.getElementsByTagName("queryNode").item(0);
      graph.add(createGeneralCategory(node));
      // System.out.println("name="+node.getNodeName());
      addRelations(graph, 0, node.getChildNodes());
      System.out.println(graph);
      System.out.println("target=" + target);

      XFacetedQuery query = searchFactory.createXFacetedQuery();
      query.setSearchTarget(target);
      query.setQueryConstraint(graph);
      query.setResultSpec(searchFactory.createXFacetedResultSpec());
      return query;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 2
0
  public void createDom()
      throws ParserConfigurationException, SAXException, IOException, TransformerException {
    String filePath = "maven_template.xml";
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(filePath);

    Node projectUrl = doc.getElementsByTagName("projectUrl").item(0);
    projectUrl.setTextContent("https://github.com/YuesongWang/TestJenkins/");

    Node url = doc.getElementsByTagName("url").item(0);
    url.setTextContent("[email protected]:YuesongWang/TestJenkins.git");

    Node credentialsId = doc.getElementsByTagName("credentialsId").item(0);
    credentialsId.setTextContent("c56c7063-12a8-4a0f-b772-83b16732f6bf");

    Node targets = doc.getElementsByTagName("targets").item(0);
    targets.setTextContent("clean install");

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("config.xml"));
    transformer.transform(source, result);
  }
Ejemplo n.º 3
0
  public void parseStatusXml(String statusXml) {
    try {
      Document statusDoc = SubmissionUtils.emptyDocument();
      SubmissionUtils.transform(new StringReader(statusXml), statusDoc);

      if (statusDoc.getDocumentElement().getTagName().equals("error")) {
        String runName = statusDoc.getElementsByTagName("RunName").item(0).getTextContent();
        String runDirRegex = "(\\d{6})_([A-z0-9]+)_(\\d+)_[A-z0-9_]*";
        Matcher m = Pattern.compile(runDirRegex).matcher(runName);
        if (m.matches()) {
          setStartDate(new SimpleDateFormat("yyMMdd").parse(m.group(1)));
          setInstrumentName(m.group(2));
        }
        setRunName(runName);
        setHealth(HealthType.Unknown);
      } else {
        String runStarted = statusDoc.getElementsByTagName("RunStarted").item(0).getTextContent();
        setStartDate(new SimpleDateFormat("EEEE, MMMMM dd, yyyy h:mm aaa").parse(runStarted));
        setInstrumentName(
            statusDoc.getElementsByTagName("InstrumentName").item(0).getTextContent());
        setRunName(statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
        setHealth(HealthType.Unknown);
      }
      setXml(statusXml);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  // factory
  private static GenerationTarget createTarget(File templateFile, File root) {
    GenerationTarget target;

    // read XML document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.parse(templateFile);

      // get name
      NodeList nodes = doc.getElementsByTagName("templates");
      Node node = nodes.item(0);
      NamedNodeMap attrs = node.getAttributes();
      Node attr = attrs.getNamedItem("name");
      String templateName = attr.getNodeValue();
      target = new GenerationTarget(templateFile, root, templateName);

      // get class directives
      nodes = doc.getElementsByTagName("project");
      int nb = nodes.getLength();
      for (int i = 0; i < nb; i++) {
        node = nodes.item(i);
        createProjectDirective(target, node);
      }

    } catch (ParserConfigurationException ex) {
      target = null;
    } catch (IOException ex) {
      target = null;
    } catch (SAXException ex) {
      target = null;
    } // end try

    return target;
  }
Ejemplo n.º 5
0
  public static Managment ManagmentParsing(String filename)
      throws SAXException, IOException, ParserConfigurationException {

    // create a doc type to read from the xml file menu
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document docInitialData = dBuilder.parse("InitialData.xml");
    Document docOrders = dBuilder.parse("OrdersList.xml");
    Document docMenu = dBuilder.parse("Menu.xml");

    Vector<Chef> Chefs = ChefsParsing(docInitialData);

    Vector<DeliveryPerson> DeliveryPersons = DeliveryPersonsParsing(docInitialData);

    Element Tools = (Element) (docInitialData.getElementsByTagName("Tools").item(0));
    Vector<Kitchen_Tool> KitchenTools = ParsingKitchenTools(Tools);

    Element Ings = (Element) (docInitialData.getElementsByTagName("Ingredients").item(0));
    Vector<Ingredient> Ingredients = ParsingIngredients(Ings);

    WarehouseImpl Warehouse = new WarehouseImpl(Ingredients, KitchenTools);

    Menu m = MenuParsing(docMenu);

    Vector<Order> Orders = OrdersParsing(m, docOrders);

    Element Address = (Element) (docInitialData.getElementsByTagName("Address").item(0));
    Address Res_Address = ParsingAddress(Address);

    return (new Managment(Chefs, Res_Address, DeliveryPersons, Orders, Warehouse, m));
  }
Ejemplo n.º 6
0
    public IsoMessageDef build() {
      Encoding mtiEncoding =
          Encoding.valueOf(
              getMandatoryAttribute(
                  (Element) doc.getElementsByTagName(ELEMENT_MTI_ENCODING).item(0), ATTR_TYPE));
      NumericCodec mtiCodec = new NumericCodec(mtiEncoding, 4);
      LOG.info("MTI encoding: {}", mtiEncoding);

      CompositeDef headerDef = null;
      SortedMap<Integer, ComponentDef> headerComponents = buildHeaderComponents();
      if (headerComponents != null) {
        headerDef = new CompositeDef(headerComponents, new FixedCompositeCodec(), true);
      }

      Bitmap.Type msgBitmapType =
          Bitmap.Type.valueOf(
              getMandatoryAttribute(
                  (Element) doc.getElementsByTagName(ELEMENT_MSG_BITMAP).item(0), ATTR_TYPE));
      LOG.info("Bitmap type: {}", msgBitmapType);
      BitmapCodec msgBitmapCodec = new BitmapCodec(msgBitmapType);
      Map<Integer, CompositeDef> fieldsDef = buildFieldsDefs(msgBitmapCodec);

      buildFieldsDefsExtension(fieldsDef);

      return new IsoMessageDef(headerDef, mtiCodec, fieldsDef);
    }
  public void testUpdate() throws Exception {
    // perform an update
    String update =
        "<wfs:Transaction service=\"WFS\" version=\"1.0.0\" "
            + "xmlns:cite=\"http://www.opengis.net/cite\" "
            + "xmlns:ogc=\"http://www.opengis.net/ogc\" "
            + "xmlns:wfs=\"http://www.opengis.net/wfs\" "
            + "xmlns:gml=\"http://www.opengis.net/gml\"> "
            + "<wfs:Update typeName=\"cite:Geometryless\" > "
            + "<wfs:Property>"
            + "<wfs:Name>name</wfs:Name>"
            + "<wfs:Value>AnotherName</wfs:Value>"
            + "</wfs:Property>"
            + "<ogc:Filter>"
            + "<ogc:FeatureId fid=\"Geometryless.2\"/>"
            + "</ogc:Filter>"
            + "</wfs:Update>"
            + "</wfs:Transaction>";

    Document dom = postAsDOM("wfs", update);
    assertTrue(dom.getElementsByTagName("wfs:SUCCESS").getLength() != 0);

    // do another get feature
    dom =
        getAsDOM(
            "wfs?request=GetFeature&typename=cite:Geometryless&version=1.0.0&service=wfs&featureId=Geometryless.2");
    assertEquals(
        "AnotherName",
        dom.getElementsByTagName("cite:name").item(0).getFirstChild().getNodeValue());
  }
Ejemplo n.º 8
0
  @Test
  public void testWithGmlObjectId() throws Exception {
    String xml =
        "<wfs:GetFeature xmlns:cdf=\"http://www.opengis.net/cite/data\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" version=\"1.1.0\" service=\"WFS\">"
            + "<wfs:Query  typeName=\"cdf:Seven\" srsName=\"urn:x-ogc:def:crs:EPSG:6.11.2:4326\">"
            + "</wfs:Query>"
            + "</wfs:GetFeature>";

    Document dom = postAsDOM("wfs", xml);
    assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName());
    assertEquals(7, dom.getElementsByTagName("cdf:Seven").getLength());

    NodeList others = dom.getElementsByTagName("cdf:Seven");
    String id = ((Element) others.item(0)).getAttributeNS(GML.NAMESPACE, "id");
    assertNotNull(id);

    xml =
        "<wfs:GetFeature xmlns:cdf=\"http://www.opengis.net/cite/data\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" version=\"1.1.0\" service=\"WFS\">"
            + "<wfs:Query  typeName=\"cdf:Seven\" srsName=\"urn:x-ogc:def:crs:EPSG:6.11.2:4326\">"
            + "<ogc:Filter>"
            + "<ogc:GmlObjectId gml:id=\""
            + id
            + "\"/>"
            + "</ogc:Filter>"
            + "</wfs:Query>"
            + "</wfs:GetFeature>";
    dom = postAsDOM("wfs", xml);

    assertEquals(1, dom.getElementsByTagName("cdf:Seven").getLength());
  }
 @Override
 protected void onPostExecute(String result) {
   super.onPostExecute(result);
   Log.d("XMLResult", result);
   try {
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     InputStream xmlData = new ByteArrayInputStream(result.getBytes());
     Document xmlDoc = dBuilder.parse(xmlData);
     ;
     int redLevel = Integer.parseInt(xmlDoc.getElementsByTagName("r").item(0).getTextContent());
     int greenLevel = Integer.parseInt(xmlDoc.getElementsByTagName("g").item(0).getTextContent());
     int blueLevel = Integer.parseInt(xmlDoc.getElementsByTagName("b").item(0).getTextContent());
     int transition =
         Integer.parseInt(xmlDoc.getElementsByTagName("lastTransition").item(0).getTextContent());
     Integer time =
         Integer.parseInt(xmlDoc.getElementsByTagName("lastTime").item(0).getTextContent());
     uiMan.setRGB(redLevel, greenLevel, blueLevel);
     uiMan.setTime(time);
     uiMan.setTransition(transition);
   } catch (ParserConfigurationException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (SAXException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (IOException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   }
 }
  /**
   * Tests that we can GET a value from the system and verify that it is within acceptable range.
   *
   * @throws Exception if GET fails
   */
  @Test
  public void testGet() throws Exception {
    PhotovoltaicsData.modifySystemState();

    // Set up the GET client
    // String getUrl = "http://localhost:7001/photovoltaic/state";
    String getUrl = "http://localhost:7001/cgi-bin/egauge?tot";
    ClientResource getClient = new ClientResource(getUrl);

    // Get the XML representation.
    DomRepresentation domRep = new DomRepresentation(getClient.get());
    Document domDoc = domRep.getDocument();

    // Grabs tags from XML.
    NodeList meterList = domDoc.getElementsByTagName("meter");
    NodeList energyList = domDoc.getElementsByTagName("energy");
    NodeList powerList = domDoc.getElementsByTagName("power");

    // Grabs attributes from tags.
    String title = ((Element) meterList.item(1)).getAttribute("title");

    // Grabs value from tags.
    String energy = ((Element) energyList.item(1)).getTextContent();
    String power = ((Element) powerList.item(1)).getTextContent();

    // Check that we are returning the correct title.
    assertEquals("Checking that title is \"Solar\"", title, "Solar");

    // Check that the returned value is within a delta of our value.
    assertEquals(1500, Double.parseDouble(energy), 1750);
    assertEquals(700, Double.parseDouble(power), 700);
  }
  public static Request createRequest(String configurationFile)
      throws ParserConfigurationException, IOException, SAXException, ParseException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(configurationFile);

    document.getDocumentElement().normalize();

    List<Header> headerList = new LinkedList<>();

    NodeList list = document.getElementsByTagName("header");

    for (int i = 0; i < list.getLength(); i++) {
      Node nNode = list.item(i);

      if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        Element eElement = (Element) nNode;
        headerList.add(
            new BasicHeader(
                eElement.getElementsByTagName("name").item(0).getTextContent(),
                eElement.getElementsByTagName("value").item(0).getTextContent()));
      }
    }

    return new Request(
        document.getDocumentElement().getAttribute("version"),
        document.getDocumentElement().getAttribute("created_by"),
        new Date(Long.parseLong(document.getDocumentElement().getAttribute("time")) * 1000),
        document.getElementsByTagName("uri").item(0).getTextContent(),
        document.getElementsByTagName("method").item(0).getTextContent(),
        headerList);
  }
Ejemplo n.º 12
0
  public void execute() throws BuildException {
    File xsltMapFile = getXsltMapFile();

    Document document = null;
    if (xsltMapFile != null && xsltMapFile.exists()) {
      document = XmlUtil.getDocument(xsltMapFile);
    }

    if (document != null) {
      NodeList inputNodeList =
          document.getElementsByTagName(TransformationDescType.INPUT.getTagName());
      if (inputNodeList != null && inputNodeList.getLength() > 0) {
        populateProviderServices(xsltMapFile.getParentFile(), inputNodeList);
      }
      NodeList outputNodeList =
          document.getElementsByTagName(TransformationDescType.OUTPUT.getTagName());
      if (outputNodeList != null && outputNodeList.getLength() > 0) {
        populateConsumerServices(xsltMapFile.getParentFile(), outputNodeList);
      }
    }
    try {

      generateTransformMap();
    } catch (IOException ex) {
      throw new BuildException(ex);
    }
  }
Ejemplo n.º 13
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

      String filename = getServletContext().getRealPath("data" + File.separator + "sampleXML2.xml");
      File fXmlFile = new File(filename);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);

      // optional, but recommended
      // read this -
      // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
      doc.getDocumentElement().normalize();

      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

      NodeList nList = doc.getElementsByTagName("task");

      NodeList nList2 = doc.getElementsByTagName("dataset");

      String dataset = ((Element) nList2.item(0)).getTextContent();

      System.out.println("The dataset is ::: " + dataset);

      System.out.println("----------------------------");

      for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          /* System.out.println("Staff id : " + eElement.getAttribute("id"));
          System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
          System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
          System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
          System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());   */

          System.out.println(
              "Name:: " + eElement.getElementsByTagName("name").item(0).getTextContent());
          System.out.println(
              "Size:: " + eElement.getElementsByTagName("size").item(0).getTextContent());
          System.out.println(
              "Time:: " + eElement.getElementsByTagName("time").item(0).getTextContent());
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();

    } finally {
      out.close();
    }
  }
Ejemplo n.º 14
0
  public void verifySchedulerFifoXML(String xml) throws JSONException, Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList nodesSched = dom.getElementsByTagName("scheduler");
    assertEquals("incorrect number of elements", 1, nodesSched.getLength());
    NodeList nodes = dom.getElementsByTagName("schedulerInfo");
    assertEquals("incorrect number of elements", 1, nodes.getLength());

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);

      verifyClusterSchedulerFifoGeneric(
          WebServicesTestUtils.getXmlAttrString(element, "xsi:type"),
          WebServicesTestUtils.getXmlString(element, "qstate"),
          WebServicesTestUtils.getXmlFloat(element, "capacity"),
          WebServicesTestUtils.getXmlFloat(element, "usedCapacity"),
          WebServicesTestUtils.getXmlInt(element, "minQueueMemoryCapacity"),
          WebServicesTestUtils.getXmlInt(element, "maxQueueMemoryCapacity"),
          WebServicesTestUtils.getXmlInt(element, "numNodes"),
          WebServicesTestUtils.getXmlInt(element, "usedNodeCapacity"),
          WebServicesTestUtils.getXmlInt(element, "availNodeCapacity"),
          WebServicesTestUtils.getXmlInt(element, "totalNodeCapacity"),
          WebServicesTestUtils.getXmlInt(element, "numContainers"));
    }
  }
Ejemplo n.º 15
0
  /**
   * Parse XML document which is assumed to be in RSS format. RSS 2.0 example:
   *
   * <p><?xml version="1.0"?> <rss version="2.0"> <channel> <title>Lift Off News</title>
   * <link>http://liftoff.msfc.nasa.gov/</link> <description>Liftoff to Space
   * Exploration.</description> <language>en-us</language> <pubDate>Tue, 10 Jun 2003 04:00:00
   * GMT</pubDate> <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
   * <docs>http://blogs.law.harvard.edu/tech/rss</docs> <generator>Weblog Editor 2.0</generator>
   * <managingEditor>[email protected]</managingEditor>
   * <webMaster>[email protected]</webMaster> <ttl>5</ttl>
   *
   * <p><item> <title>Star City</title>
   * <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link> <description>How do
   * Americans get ready to work with Russians aboard the International Space Station? They take a
   * crash course in culture, language and protocol at Russia's Star City.</description>
   * <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
   * <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid> </item>
   *
   * <p><item> <title>Space Exploration</title> <link>http://liftoff.msfc.nasa.gov/</link>
   * <description>Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a
   * partial eclipse of the Sun on Saturday, May 31.</description> <pubDate>Fri, 30 May 2003
   * 11:06:42 GMT</pubDate> <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
   * </item>
   *
   * <p></channel> </rss>
   *
   * @param sitemap
   * @param doc
   */
  private void parseRSS(SiteMap sitemap, Document doc) {

    // Grab items from <item><link>URL</link></item>
    // and last modified date from <pubDate>DATE</pubDate>

    LOG.debug("Parsing RSS doc");
    sitemap.setType(SitemapType.RSS);
    NodeList list = doc.getElementsByTagName("channel");
    Element elem = (Element) list.item(0);

    // Treat publication date as last mod (Tue, 10 Jun 2003 04:00:00 GMT)
    String lastMod = getElementValue(elem, "pubDate");
    LOG.debug("lastMod = ", lastMod);

    list = doc.getElementsByTagName("item");
    // Loop through the <item>s
    for (int i = 0; i < list.getLength() && i < MAX_URLS; i++) {

      Node n = list.item(i);
      if (n.getNodeType() == Node.ELEMENT_NODE) {
        elem = (Element) n;
        String link = getElementValue(elem, "link");

        addUrlIntoSitemap(link, sitemap, lastMod, null, null, i);
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Handles the loading of defined styles from the style.xml file as well as automatic styles from
   * the content.xml file.
   *
   * <p>Any change to a defined style, such as a short bold section, falls into the latter category.
   */
  protected void loadStyles(SxcDocument sxcDoc) {

    styleCat = new StyleCatalog(25);
    NodeList nl = null;
    String families[] =
        new String[] {
          SxcConstants.COLUMN_STYLE_FAMILY,
          SxcConstants.ROW_STYLE_FAMILY,
          SxcConstants.TABLE_CELL_STYLE_FAMILY
        };
    Class<?> classes[] = new Class[] {ColumnStyle.class, RowStyle.class, CellStyle.class};
    /*
     * Process the content XML for any other style info.
     */
    org.w3c.dom.Document contentDom = sxcDoc.getContentDOM();
    nl = contentDom.getElementsByTagName(TAG_OFFICE_AUTOMATIC_STYLES);
    if (nl.getLength() != 0) {
      styleCat.add(nl.item(0), families, classes, null, false);
    }

    org.w3c.dom.Document stylesDom = sxcDoc.getStyleDOM();
    nl = stylesDom.getElementsByTagName(TAG_OFFICE_STYLES);
    if (nl.getLength() != 0) {
      styleCat.add(nl.item(0), families, classes, null, false);
    }
  }
Ejemplo n.º 17
0
	protected void SaveDirectory(Document doc) throws TransformerException, ParserConfigurationException {
		
		String xmlStr = OperateXMLByDOM.doc2FormatString(doc);
		AsciiSaveUtil.saveAscii(outDir+"tree.xml", xmlStr);

		// hack的方法, 给每个目录加一个空节点
		List<Node> nl2 = new ArrayList<Node>();
		nl2.add(doc.getElementsByTagName("root").item(0));
		NodeList nl = doc.getElementsByTagName("children");
		for (int i = 0; i < nl.getLength(); i++) {
			if (((Element)nl.item(i)).getAttribute("id") == "")
				nl2.add(nl.item(i));
		}
		for (Node node: nl2){
			node.appendChild(doc.createElement("children"));
		}
		
		xmlStr = OperateXMLByDOM.doc2FormatString(doc);
		JSONObject soapDatainJsonObject = XML.toJSONObject(xmlStr);
				String jsonString = soapDatainJsonObject.toString();
		
		// 通过字符替换把这些空节点去掉,以达到产生[]括号对的目的
		String tmp = jsonString.replaceAll(",\\\"\\\"", "");
		String json = "["+tmp.substring(8, tmp.length()-1)+"]";
		AsciiSaveUtil.saveAscii(outDir+"tree.json", json);
	}
Ejemplo n.º 18
0
  public FilterConfBean parseConfig(String filterConfFileName) throws Exception {
    // 载入filter配置文件
    InputStream is = loadFile(filterConfFileName);
    if (is == null) {
      return null;
    }

    // byte[] data = new byte[1024];
    // int index = is.read(data);
    // System.out.println(new String(data));

    FilterConfBean filterConfBean = new FilterConfBean();
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = fac.newDocumentBuilder();
    Document doc = builder.parse(is);
    NodeList nodeList = doc.getElementsByTagName(FilterConfElementEnum.ELEMENT_CHAIN.getValue());
    Map<String, List<FilterDescBean>> chainMap = new HashMap<String, List<FilterDescBean>>();
    for (int i = 0; i < nodeList.getLength(); i++) {
      Element chainElement = (Element) nodeList.item(i);
      List<FilterDescBean> chain = parseChain(chainElement);
      chainMap.put(
          chainElement.getAttribute(FilterConfElementEnum.ELEMENT_ATTRBUTE_NAME.getValue()), chain);
    }

    nodeList = doc.getElementsByTagName(FilterConfElementEnum.ELEMENT_EXTENTION.getValue());
    for (int i = 0; i < nodeList.getLength(); i++) {
      if (nodeList.item(i) instanceof Element
          && ((Element) nodeList.item(i)).getAttribute("value") != null
          && ((Element) nodeList.item(i)).getAttribute("value").equalsIgnoreCase("true")) {
        filterConfBean.setExtension(true);
      }
    }
    filterConfBean.setChainMap(chainMap);
    return filterConfBean;
  }
Ejemplo n.º 19
0
  protected void loadXmlResourceFile() {
    try {
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      log.info(
          "file://"
              + WebMailServer.getServer().getProperty("webmail.template.path")
              + System.getProperty("file.separator")
              + getXmlResourceFilename());
      xmlRoot =
          parser.parse(
              "file://"
                  + WebMailServer.getServer().getProperty("webmail.template.path")
                  + System.getProperty("file.separator")
                  + getXmlResourceFilename());

      NodeList nl = xmlRoot.getElementsByTagName("COMMON");
      if (nl.getLength() > 0) {
        elem_common = (Element) nl.item(0);
      }

      nl = xmlRoot.getElementsByTagName("LOCALE");
      if (nl.getLength() > 0) {
        elementBundle = (Element) nl.item(0);
      }
    } catch (IOException e) {
      log.error(e);
    } catch (SAXException e) {
      log.error(e);
    } catch (ParserConfigurationException e) {
      log.error(e);
    } // We don't want to throw for these exceptions?
  }
Ejemplo n.º 20
0
  private ArrayList<Forecast> buildForecasts(String raw) throws Exception {
    ArrayList<Forecast> forecasts = new ArrayList<Forecast>();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));
    NodeList times = doc.getElementsByTagName("start-valid-time");

    for (int i = 0; i < times.getLength(); i++) {
      Element time = (Element) times.item(i);
      Forecast forecast = new Forecast();

      forecasts.add(forecast);
      forecast.setTime(time.getFirstChild().getNodeValue());
    }

    NodeList temps = doc.getElementsByTagName("value");

    for (int i = 0; i < temps.getLength(); i++) {
      Element temp = (Element) temps.item(i);
      Forecast forecast = forecasts.get(i);

      forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }

    NodeList icons = doc.getElementsByTagName("icon-link");

    for (int i = 0; i < icons.getLength(); i++) {
      Element icon = (Element) icons.item(i);
      Forecast forecast = forecasts.get(i);

      forecast.setIcon(icon.getFirstChild().getNodeValue());
    }

    return (forecasts);
  }
  public void testInsert() throws Exception {
    // perform an insert
    String insert =
        "<wfs:Transaction service=\"WFS\" version=\"1.0.0\" "
            + "xmlns:cite=\"http://www.opengis.net/cite\" "
            + "xmlns:ogc=\"http://www.opengis.net/ogc\" "
            + "xmlns:wfs=\"http://www.opengis.net/wfs\" "
            + "xmlns:gml=\"http://www.opengis.net/gml\"> "
            + "<wfs:Insert > "
            + "<cite:Geometryless fid=\"Geometryless.4\">"
            + "<cite:name>Gimbo</cite:name>"
            + "<cite:number>1000</cite:number>"
            + "</cite:Geometryless>"
            + "</wfs:Insert>"
            + "</wfs:Transaction>";

    Document dom = postAsDOM("wfs", insert);
    print(dom);
    assertTrue(dom.getElementsByTagName("wfs:SUCCESS").getLength() != 0);
    assertTrue(dom.getElementsByTagName("wfs:InsertResult").getLength() != 0);

    // do another get feature
    dom = getAsDOM("wfs?request=GetFeature&typename=cite:Geometryless&version=1.0.0&service=wfs");
    assertEquals(4, dom.getElementsByTagName("cite:Geometryless").getLength());
  }
Ejemplo n.º 22
0
  @Test
  public void testTasksXML() throws JSONException, Exception {

    WebResource r = resource();
    Map<JobId, Job> jobsMap = appContext.getAllJobs();
    for (JobId id : jobsMap.keySet()) {
      String jobId = MRApps.toString(id);
      ClientResponse response =
          r.path("ws")
              .path("v1")
              .path("history")
              .path("mapreduce")
              .path("jobs")
              .path(jobId)
              .path("tasks")
              .accept(MediaType.APPLICATION_XML)
              .get(ClientResponse.class);
      assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
      String xml = response.getEntity(String.class);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      Document dom = db.parse(is);
      NodeList tasks = dom.getElementsByTagName("tasks");
      assertEquals("incorrect number of elements", 1, tasks.getLength());
      NodeList task = dom.getElementsByTagName("task");
      verifyHsTaskXML(task, jobsMap.get(id));
    }
  }
Ejemplo n.º 23
0
 private static Vector<DeliveryPerson> DeliveryPersonsParsing(Document doc) {
   Vector<DeliveryPerson> DeliveryPersons = new Vector<DeliveryPerson>();
   NodeList nList =
       doc.getElementsByTagName(
           "DeliveryPerson"); // we create a nodelist of all the chefs in the file
   for (int temp = 0; temp < nList.getLength(); temp++) {
     Element e =
         (Element) (nList.item(temp)); // create an element with only one DeliveryPerson info
     String name =
         e.getElementsByTagName("name")
             .item(0)
             .getTextContent(); // get the name of the DeliveryPerson
     int Speed =
         Integer.parseInt(
             e.getElementsByTagName("speed")
                 .item(0)
                 .getTextContent()); // get the speed  of this DeliveryPerson
     Address Restaurant_Address =
         ParsingAddress((Element) (doc.getElementsByTagName("Address").item(0)));
     DeliveryPersons.add(
         new DeliveryPerson(
             name,
             Speed,
             Restaurant_Address)); // add a new DeliveryPerson into the vector that we return
   } // end for temp
   return DeliveryPersons;
 } // end DeliveryPersonsParsing
Ejemplo n.º 24
0
  public void testCreateMusteriSchemaModel() throws Exception {
    // create an instance of Musteri schema model
    POSchemaManager musteriSchemaManager = MusteriSchemaManager.getInstance();
    // create a musteri model...
    Document musteriModel = musteriSchemaManager.getSchemaModel();

    // asserting musteri model isnot null
    assertNotNull(musteriModel);

    // get the schema element..
    Element schemaElement = musteriModel.getDocumentElement();
    // assert that schema element is not null
    assertNotNull(schemaElement);

    // get the complex type..
    Element musteriComplexType =
        (Element) musteriModel.getElementsByTagName(XSD_PREFIX + ":" + COMPLEX_TYPE).item(0);
    // assert personel complex type element is not null...
    assertNotNull(musteriComplexType);

    // get sequence element..
    Element sequenceElement =
        (Element) musteriModel.getElementsByTagName(XSD_PREFIX + ":" + SEQUENCE).item(0);
    // assert sequence element is not null...
    assertNotNull(sequenceElement);

    // get adSoyad element from sequence element...
    Element firstElementOfSequence = (Element) sequenceElement.getFirstChild();
    // assert name and the type are equal..
    assertEquals("adSoyad", firstElementOfSequence.getAttribute(NAME));
    assertEquals("xsd:" + "string", firstElementOfSequence.getAttribute(TYPE));

    // assert number of the elements are equal to 4.
    assertEquals(4, sequenceElement.getElementsByTagName("xsd:" + ELEMENT).getLength());
  }
Ejemplo n.º 25
0
  public static void lerPeloDOM() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse("src/venda.xml");

    NodeList formasPagamento = document.getElementsByTagName("formaDePagamento");
    System.out.println(formasPagamento.item(0).getTextContent());

    String moeda = document.getDocumentElement().getAttribute("moeda");
    System.out.println(moeda);

    NodeList produtos = document.getElementsByTagName("produto");
    for (int i = 0; i < produtos.getLength(); i++) {
      Element produtoElement = (Element) produtos.item(i);
      String nome = produtoElement.getElementsByTagName("nome").item(0).getTextContent();
      double preco =
          Double.parseDouble(produtoElement.getElementsByTagName("preco").item(0).getTextContent());

      Produto produto = new Produto(nome, preco);

      System.out.println(produto);
    }
  }
Ejemplo n.º 26
0
  /**
   * Parse the given XML content.
   *
   * @param sitemapUrl
   * @param is
   * @throws UnknownFormatException
   */
  private AbstractSiteMap processXml(URL sitemapUrl, InputSource is) throws UnknownFormatException {

    Document doc = null;

    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      doc = dbf.newDocumentBuilder().parse(is);
    } catch (Exception e) {
      LOG.debug(e.toString());
      throw new UnknownFormatException("Error parsing XML for: " + sitemapUrl);
    }

    // See if this is a sitemap index
    NodeList nodeList = doc.getElementsByTagName("sitemapindex");
    if (nodeList.getLength() > 0) {
      nodeList = doc.getElementsByTagName("sitemap");
      return parseSitemapIndex(sitemapUrl, nodeList);
    } else if (doc.getElementsByTagName("urlset").getLength() > 0) {
      // This is a regular Sitemap
      return parseXmlSitemap(sitemapUrl, doc);
    } else if (doc.getElementsByTagName("link").getLength() > 0) {
      // Could be RSS or Atom
      return parseSyndicationFormat(sitemapUrl, doc);
    }

    throw new UnknownFormatException("Unknown XML format for: " + sitemapUrl);
  }
Ejemplo n.º 27
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.º 28
0
  /**
   * Parse the XML document, looking for a <b>feed</b> element to determine if it's an <b>Atom
   * doc</b> <b>rss</b> to determine if it's an <b>RSS doc</b>.
   *
   * @param sitemapUrl
   * @param doc - XML document to parse
   * @throws UnknownFormatException if XML does not appear to be Atom or RSS
   */
  private SiteMap parseSyndicationFormat(URL sitemapUrl, Document doc)
      throws UnknownFormatException {

    SiteMap sitemap = new SiteMap(sitemapUrl);

    // See if this is an Atom feed by looking for "feed" element
    NodeList list = doc.getElementsByTagName("feed");
    if (list.getLength() > 0) {
      parseAtom(sitemap, (Element) list.item(0), doc);
      sitemap.setProcessed(true);
      return sitemap;
    } else {
      // See if it is a RSS feed by looking for a "channel" element. This avoids the issue
      // of having the outer tag named <rdf:RDF> that was causing this code to fail. Inside of
      // the <rss> or <rdf> tag is a <channel> tag, so we can use that.
      // See https://github.com/crawler-commons/crawler-commons/issues/87
      // and also RSS 1.0 specification http://web.resource.org/rss/1.0/spec
      list = doc.getElementsByTagName("channel");
      if (list.getLength() > 0) {
        parseRSS(sitemap, doc);
        sitemap.setProcessed(true);
        return sitemap;
      } else {
        throw new UnknownFormatException("Unknown syndication format at " + sitemapUrl);
      }
    }
  }
Ejemplo n.º 29
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.º 30
0
  @Test
  public void testRequestWithMissingContentType() throws InterruptedException {

    AssertEndpointResponseBuilder assertResponseBuilder = applyPolicyAndTest();

    assertResponseBuilder
        .clear()
        .requestHeader("Content-type", "application/json")
        .requestHeader(
            "Authorization",
            "Basic " + Base64.getEncoder().encodeToString((USER + ":" + PASSWORD).getBytes()))
        .setPayload(SOAP_REQUEST)
        .setExpectedStatus(200)
        .assertResponse();

    logger.debug("Response payload: " + assertResponseBuilder.getResponseBody());
    try {
      Document xmlDocument = createXMLDocument(assertResponseBuilder.getResponseBody());
      assertFalse(
          "Security element should not be present",
          xmlDocument.getElementsByTagName("wsse:Security").getLength() > 0);
      assertFalse(
          "Username element should not be present",
          xmlDocument.getElementsByTagName("wsse:Username").getLength() > 0);
      assertFalse(
          "Password element should not be present",
          xmlDocument.getElementsByTagName("wsse:Password").getLength() > 0);
    } catch (ParserConfigurationException | SAXException | IOException e) {
      e.printStackTrace();
      assertTrue("Error processing XML", false);
    }
  }