Example #1
0
  /**
   * Runs an XPath expression on this node.
   *
   * @param env
   * @param expression
   * @return array of results
   * @throws XPathExpressionException
   */
  public Value xpath(Env env, String expression) {
    try {
      XPath xpath = XPathFactory.newInstance().newXPath();

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

      int nodeLength = nodes.getLength();

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

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

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

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

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

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

      return NullValue.NULL;
    }
  }
  private void loadDecoratorMappers(NodeList nodes) {
    clearDecoratorMappers();
    Properties emptyProps = new Properties();

    pushDecoratorMapper("com.opensymphony.module.sitemesh.mapper.NullDecoratorMapper", emptyProps);

    // note, this works from the bottom node up.
    for (int i = nodes.getLength() - 1; i > 0; i--) {
      if (nodes.item(i) instanceof Element) {
        Element curr = (Element) nodes.item(i);
        if ("mapper".equalsIgnoreCase(curr.getTagName())) {
          String className = curr.getAttribute("class");
          Properties props = new Properties();
          // build properties from <param> tags.
          NodeList children = curr.getChildNodes();
          for (int j = 0; j < children.getLength(); j++) {
            if (children.item(j) instanceof Element) {
              Element currC = (Element) children.item(j);
              if ("param".equalsIgnoreCase(currC.getTagName())) {
                String value = currC.getAttribute("value");
                props.put(currC.getAttribute("name"), replaceProperties(value));
              }
            }
          }
          // add mapper
          pushDecoratorMapper(className, props);
        }
      }
    }

    pushDecoratorMapper(
        "com.opensymphony.module.sitemesh.mapper.InlineDecoratorMapper", emptyProps);
  }
Example #3
0
  private String[] processArgs(NodeList nodes) {
    int len = nodes.getLength() - 1;
    String[] list;
    int arg_count = 0;
    int current = 0;

    for (int i = 0; i <= len; i++) {
      String name = nodes.item(i).getNodeName();
      if (name.contains("arg")) {
        arg_count += 1;
      }
    }

    list = new String[arg_count];

    for (int i = 0; i <= len; i++) {
      String name = nodes.item(i).getNodeName();
      if (name.contains("arg")) {
        String value = nodes.item(i).getTextContent();
        list[current] = value;
        current += 1;
      }
    }

    return list;
  }
Example #4
0
  private void parseReporting(Element configRoot, LocalBenchmark localBenchmark) {
    Element reportsEl = (Element) configRoot.getElementsByTagName("reports").item(0);
    NodeList reportElList = reportsEl.getElementsByTagName("report");
    for (int i = 0; i < reportElList.getLength(); i++) {
      if (reportElList.item(i) instanceof Element) {
        ReportDesc reportDesc = new ReportDesc();
        Element thisReportEl = (Element) reportElList.item(i);
        if (thisReportEl.getAttribute("includeAll") != null) {
          String inclAll = ConfigHelper.getStrAttribute(thisReportEl, "includeAll");
          if (inclAll.equalsIgnoreCase("true")) {
            reportDesc.setIncludeAll(true);
            reportDesc.addReportItems(all);
            localBenchmark.addReportDesc(reportDesc);
            reportDesc.setReportName(ConfigHelper.getStrAttribute(thisReportEl, "name"));
            continue;
          }
        }

        NodeList itemsEl = thisReportEl.getElementsByTagName("item");
        for (int j = 0; j < itemsEl.getLength(); j++) {
          Element itemEl = (Element) itemsEl.item(j);
          String productName = ConfigHelper.getStrAttribute(itemEl, "product");
          String productConfig = ConfigHelper.getStrAttribute(itemEl, "config");
          reportDesc.addReportItem(productName, productConfig);
        }
        reportDesc.setReportName(ConfigHelper.getStrAttribute(thisReportEl, "name"));
        localBenchmark.addReportDesc(reportDesc);
      }
    }
  }
 private Map readMap(Element l) {
   Map map = new HashMap();
   NodeList nodes = l.getChildNodes();
   Set roles = new HashSet();
   for (int i = 0; i < nodes.getLength(); i++) {
     Node item = nodes.item(i);
     if (item instanceof Element) {
       String key = item.getNodeName();
       StringBuffer value = new StringBuffer();
       NodeList vals = item.getChildNodes();
       for (int j = 0; j < vals.getLength(); j++) {
         Node val = vals.item(j);
         if (val instanceof Text) {
           value.append(val.getNodeValue());
         }
       }
       String val = value.toString();
       if (ROLE_ASSIGNMENT.equals(key)) {
         roles.add(val);
       } else {
         map.put(key, val);
       }
     }
   }
   if (roles.size() != 0) {
     map.put(ROLE_ASSIGNMENT, roles);
   }
   return map;
 }
Example #6
0
  public void delete()
      throws ParserConfigurationException, SAXException, IOException, TransformerException {
    Document document = new GetDocument().getDocument();
    Element rootElement = document.getDocumentElement();
    NodeList contacts = rootElement.getChildNodes();

    System.out.println("Enter the name of the contact to delete: ");
    BufferedReader inItem = new BufferedReader(new InputStreamReader(System.in));
    String contactToDelete = inItem.readLine();

    boolean isContactFound = false;

    for (int i = 0; i < contacts.getLength(); i++) {
      Node contact = contacts.item(i);
      NodeList contactData = contact.getChildNodes();

      for (int j = 0; j < contactData.getLength(); j++) {
        Node dataNode = contactData.item(j);
        if (dataNode.getNodeName().equals("name")
            && dataNode.getTextContent().equals(contactToDelete)) {
          contact.getParentNode().removeChild(contact);
          isContactFound = true;
          System.out.println("The contact " + contactToDelete + " has been deleted.");
        }
      }
    }
    Transform.transform(document);

    if (!isContactFound) System.out.println("No such contact found.");
  }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    NodeList elementList;
    Node employeeNode;
    Node childNode;
    NodeList childNodes;
    int nodeType;
    String childName;
    java.util.List actual = new java.util.ArrayList();

    java.util.List expected = new java.util.ArrayList();
    expected.add("em");
    expected.add("strong");
    expected.add("code");
    expected.add("sup");
    expected.add("var");
    expected.add("acronym");

    doc = (Document) load("hc_staff", false);
    elementList = doc.getElementsByTagName("p");
    employeeNode = elementList.item(1);
    childNodes = employeeNode.getChildNodes();
    for (int indexN1006C = 0; indexN1006C < childNodes.getLength(); indexN1006C++) {
      childNode = (Node) childNodes.item(indexN1006C);
      nodeType = (int) childNode.getNodeType();
      childName = childNode.getNodeName();

      if (equals(1, nodeType)) {
        actual.add(childName);
      } else {
        assertEquals("textNodeType", 3, nodeType);
      }
    }
    assertEqualsAutoCase("element", "elementNames", expected, actual);
  }
Example #8
0
  private void parseEvents(Element element) throws NumberFormatException, IOException {

    NodeList nodeListGpsUpdates = element.getElementsByTagName("GpsUpdate");

    if ((nodeListGpsUpdates != null) && (nodeListGpsUpdates.getLength() > 0)) {

      for (int i = 0; i < nodeListGpsUpdates.getLength(); i++) {

        Element e = (Element) nodeListGpsUpdates.item(i);

        EventNodeGps eventNodeGps = this.getEventNodeGps(e);

        this.events.add(eventNodeGps);
      }
    }

    NodeList nodeListMagnetometerUpdates = element.getElementsByTagName("MagnetometerUpdate");

    if ((nodeListMagnetometerUpdates != null) && (nodeListMagnetometerUpdates.getLength() > 0)) {

      for (int i = 0; i < nodeListMagnetometerUpdates.getLength(); i++) {

        Element e = (Element) nodeListMagnetometerUpdates.item(i);

        EventNodeMagnetometer eventNodeMagnetometer = this.getEventNodeMagnetometer(e);

        this.events.add(eventNodeMagnetometer);
      }
    }
  }
  public static void main(String argv[]) {

    try {
      File file = new File("i:\\MyXMLFile.xml");
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(file);
      doc.getDocumentElement().normalize();
      System.out.println("Root element " + doc.getDocumentElement().getNodeName());
      NodeList nodeLst = doc.getElementsByTagName("employee");
      System.out.println("Information of all employees");

      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);

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

          Element fstElmnt = (Element) fstNode;
          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
          NodeList fstNm = fstNmElmnt.getChildNodes();
          System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
          NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
          Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
          NodeList lstNm = lstNmElmnt.getChildNodes();
          System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #10
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);
    }
  }
Example #11
0
 public void parserXml(String fileName) {
   try {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document document = db.parse(fileName);
     NodeList employees = document.getChildNodes();
     for (int i = 0; i < employees.getLength(); i++) {
       Node employee = employees.item(i);
       NodeList employeeInfo = employee.getChildNodes();
       for (int j = 0; j < employeeInfo.getLength(); j++) {
         Node node = employeeInfo.item(j);
         NodeList employeeMeta = node.getChildNodes();
         for (int k = 0; k < employeeMeta.getLength(); k++) {
           System.out.println(
               employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent());
         }
       }
     }
     System.out.println("解析完毕");
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println(e.getMessage());
   } catch (SAXException e) {
     System.out.println(e.getMessage());
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
Example #12
0
  /** Loads info from xml that is supplied as an argument to the internal data objects. */
  public void loadXML(final String xml) {
    final Document document = getXMLDocument(xml);
    if (document == null) {
      return;
    }
    /* get root <drbdgui> */
    final Node rootNode = getChildNode(document, "drbdgui");
    final Map<String, List<Host>> hostMap = new LinkedHashMap<String, List<Host>>();
    if (rootNode != null) {
      /* download area */
      final String downloadUser = getAttribute(rootNode, DOWNLOAD_USER_ATTR);
      final String downloadPasswd = getAttribute(rootNode, DOWNLOAD_PASSWD_ATTR);
      if (downloadUser != null && downloadPasswd != null) {
        Tools.getConfigData().setDownloadLogin(downloadUser, downloadPasswd, true);
      }
      /* hosts */
      final Node hostsNode = getChildNode(rootNode, "hosts");
      if (hostsNode != null) {
        final NodeList hosts = hostsNode.getChildNodes();
        if (hosts != null) {
          for (int i = 0; i < hosts.getLength(); i++) {
            final Node hostNode = hosts.item(i);
            if (hostNode.getNodeName().equals(HOST_NODE_STRING)) {
              final String nodeName = getAttribute(hostNode, HOST_NAME_ATTR);
              final String sshPort = getAttribute(hostNode, HOST_SSHPORT_ATTR);
              final String color = getAttribute(hostNode, HOST_COLOR_ATTR);
              final String useSudo = getAttribute(hostNode, HOST_USESUDO_ATTR);
              final Node ipNode = getChildNode(hostNode, "ip");
              String ip = null;
              if (ipNode != null) {
                ip = getText(ipNode);
              }
              final Node usernameNode = getChildNode(hostNode, "user");
              final String username = getText(usernameNode);
              setHost(
                  hostMap, username, nodeName, ip, sshPort, color, "true".equals(useSudo), true);
            }
          }
        }
      }

      /* clusters */
      final Node clustersNode = getChildNode(rootNode, "clusters");
      if (clustersNode != null) {
        final NodeList clusters = clustersNode.getChildNodes();
        if (clusters != null) {
          for (int i = 0; i < clusters.getLength(); i++) {
            final Node clusterNode = clusters.item(i);
            if (clusterNode.getNodeName().equals("cluster")) {
              final String clusterName = getAttribute(clusterNode, CLUSTER_NAME_ATTR);
              final Cluster cluster = new Cluster();
              cluster.setName(clusterName);
              Tools.getConfigData().addClusterToClusters(cluster);
              loadClusterHosts(clusterNode, cluster, hostMap);
            }
          }
        }
      }
    }
  }
Example #13
0
  public static void readXpath()
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

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

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap nodeMap = nodes.item(i).getAttributes();
      String attrName = "";
      for (int j = 0; j < nodeMap.getLength(); j++) {
        attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("="));
        if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) {
          System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue());
        }
      }
    }
  }
 private void configure() {
   NodeList PEPList;
   Node pepNode;
   User2PEPs = new Hashtable<String, Vector<PEP>>();
   pepVect = new Vector<PEP>();
   PEPList = config.getDocumentElement().getElementsByTagName("PEP");
   int NumOfPEPS = PEPList.getLength();
   pepVect = new Vector<PEP>(NumOfPEPS);
   for (int i = 0; i < NumOfPEPS; i++) {
     pepNode = PEPList.item(i);
     String ip = pepNode.getAttributes().getNamedItem("ip").getNodeValue();
     String domain = pepNode.getAttributes().getNamedItem("domain").getNodeValue();
     long upbw = Long.parseLong(pepNode.getAttributes().getNamedItem("upbw").getNodeValue());
     long dobw = Long.parseLong(pepNode.getAttributes().getNamedItem("dobw").getNodeValue());
     PEP pep = new PEP(ip, domain, upbw, dobw);
     pepVect.add(pep);
     NodeList userList = pepNode.getChildNodes();
     for (int j = 0; j < userList.getLength(); j++) {
       Node userNode = userList.item(j);
       if (userNode.getNodeName() == "User") {
         String userIP = userNode.getAttributes().getNamedItem("ip").getNodeValue();
         Vector<PEP> up = User2PEPs.get(userIP);
         if (up == null) {
           up = new Vector<PEP>(1);
         }
         up.add(pep);
         User2PEPs.put(userIP, up);
       }
     }
   }
 }
 private double[] retrieveFcReadings(NodeList cycleList) {
   // Check the the first cycle is cycle #1, else throw an error dialog
   Element firstCycleElement = (Element) cycleList.item(0);
   String firstCycleNumber = firstCycleElement.getAttribute("X");
   if (!firstCycleNumber.contains("1")) {
     // TODO present an error dialog and terminate import
     // ...pretty harsh but this is essential for baseline subtraction
   }
   NumberFormat numFormat =
       NumberFormat.getInstance(); // Need to convert comma decimal seperators to periods
   ArrayList<Double> fcDataSet = Lists.newArrayList();
   // Cycle through the cycles and collect the Fc readings
   for (int j = 0; j < cycleList.getLength(); j++) {
     // This assumes that the first cycle is cycle 1
     Element cycleElement = (Element) cycleList.item(j);
     try {
       // NumberFormat needed to prevent locale differences in numbers (e.g. comma vs period)
       Number value = numFormat.parse(cycleElement.getAttribute("Y"));
       fcDataSet.add(value.doubleValue());
     } catch (Exception e) {
     }
   }
   double[] fcArray = new double[fcDataSet.size()];
   for (int k = 0; k < fcDataSet.size(); k++) {
     fcArray[k] = fcDataSet.get(k);
   }
   return fcArray;
 }
  public static void main(String argv[]) {

    try {

      File fXmlFile = new File(DOCUMENTS_DIR + File.separator + "matching_tasks.xml");

      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 taskList = doc.getDocumentElement().getChildNodes();
      for (int i = 0; i < taskList.getLength(); i++) {
        Node currentNode = taskList.item(i);
        if (currentNode.getNodeName().equals("task")) doTasks(taskList.item(i));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #17
0
 /**
  * Prints the given element.
  *
  * @param element the element to print
  */
 public void print(Element element) {
   // Ensure extra whitespace is not emitted next to a Text node,
   // as that will result in a situation where the restored text data is not the
   // same as the saved text data.
   boolean hasChildren = element.hasChildNodes();
   startTag(element, hasChildren);
   if (hasChildren) {
     tab++;
     boolean prevWasText = false;
     NodeList children = element.getChildNodes();
     for (int i = 0; i < children.getLength(); i++) {
       Node node = children.item(i);
       if (node instanceof Element) {
         if (!prevWasText) {
           println();
           printTabulation();
         }
         print((Element) children.item(i));
         prevWasText = false;
       } else if (node instanceof Text) {
         print(getEscaped(node.getNodeValue()));
         prevWasText = true;
       }
     }
     tab--;
     if (!prevWasText) {
       println();
       printTabulation();
     }
     endTag(element);
   }
 }
Example #18
0
  public static Message parseMessage(Document document) {
    NodeList childs = document.getDocumentElement().getChildNodes();

    boolean isMessage = false;
    boolean success = false;
    String text = "";

    for (int i = 0; i < childs.getLength(); i++) {
      if (childs.item(i) instanceof Element) {
        Element el = (Element) childs.item(i);

        if (el.getNodeName().equals("text") || el.getNodeName().equals("message")) {
          text = el.getTextContent();
        }

        if (el.getNodeName().equals("success")) {
          isMessage = true;

          success = Boolean.parseBoolean(el.getTextContent());
        }
      }
    }

    if (isMessage) {
      return new Message(success, text);
    }

    return null;
  }
Example #19
0
  private static List<Element> getTopLevelElementChildren(
      Element element, String parentName, String childrenName) throws TikaException {
    Node parentNode = null;
    if (parentName != null) {
      // Should be only zero or one <parsers> / <detectors> etc tag
      NodeList nodes = element.getElementsByTagName(parentName);
      if (nodes.getLength() > 1) {
        throw new TikaException("Properties may not contain multiple " + parentName + " entries");
      } else if (nodes.getLength() == 1) {
        parentNode = nodes.item(0);
      }
    } else {
      // All children directly on the master element
      parentNode = element;
    }

    if (parentNode != null) {
      // Find only the direct child parser/detector objects
      NodeList nodes = parentNode.getChildNodes();
      List<Element> elements = new ArrayList<Element>();
      for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node instanceof Element) {
          Element nodeE = (Element) node;
          if (childrenName.equals(nodeE.getTagName())) {
            elements.add(nodeE);
          }
        }
      }
      return elements;
    } else {
      // No elements of this type
      return Collections.emptyList();
    }
  }
Example #20
0
  public void processXMLDelete(String content) throws ClientProtocolException, IOException {

    try {
      // Log.i(TAG,"Content =" + content);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new InputSource(new StringReader(content)));
      doc.getDocumentElement().normalize();

      NodeList nodeList = doc.getElementsByTagName("results");

      /** Assign String array length by arraylist size */
      succeed = new String[nodeList.getLength()];

      for (int i = 0; i < nodeList.getLength(); i++) {

        Node node = nodeList.item(i);

        Element fstElmnt = (Element) node;

        NodeList succeedList = fstElmnt.getElementsByTagName("succeed");
        Element succeedElement = (Element) succeedList.item(0);
        succeedList = succeedElement.getChildNodes();
        succeed[i] = ((Node) succeedList.item(0)).getNodeValue();
      }
    } catch (Exception e) {
      System.out.println("XML Pasing Excpetion = " + e);
    }
  }
Example #21
0
 protected void load(Element root) throws Exception {
   NodeList list;
   int i;
   list = WSHelper.getElementChildren(root, "Messages");
   if (list != null) {
     for (i = 0; i < list.getLength(); i++) {
       Element nc = (Element) list.item(i);
       _Messages.addElement(JanusMessageInfo.loadFrom(nc));
     }
   }
   list = WSHelper.getElementChildren(root, "Rating");
   if (list != null) {
     for (i = 0; i < list.getLength(); i++) {
       Element nc = (Element) list.item(i);
       _Rating.addElement(JanusRatingInfo.loadFrom(nc));
     }
   }
   list = WSHelper.getElementChildren(root, "Moderate");
   if (list != null) {
     for (i = 0; i < list.getLength(); i++) {
       Element nc = (Element) list.item(i);
       _Moderate.addElement(JanusModerateInfo.loadFrom(nc));
     }
   }
 }
Example #22
0
  private void persistNewsData(NodeList titles, NodeList links, NodeList descriptions) {
    // Persists news data feed.
    // Also clears out previously persisted news feed data

    PersistenceManager pm = PMF.get().getPersistenceManager();
    javax.jdo.Query query = pm.newQuery(NewsItem.class);
    Long res = query.deletePersistentAll();

    System.out.println("Datastore deleted  " + res + "records");

    pm = PMF.get().getPersistenceManager();

    try {
      for (int i = 1; i < titles.getLength(); i++) {
        NewsItem ni = new NewsItem();
        ni.setTitle(titles.item(i).getTextContent());
        ni.setLink(links.item(i).getTextContent());
        if (descriptions.item(i) != null) {
          ni.setDescription(new Text(descriptions.item(i).getTextContent()));
        }
        pm.makePersistent(ni);
      }
    } finally {
      pm.close();
    }
  }
  @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());
      }
    }
  }
Example #24
0
  /**
   * Pretty prints a node.
   *
   * @param doc The document the node comes from.
   * @param node The node that should be pretty printed.
   */
  public static void prettyPrint(Document doc, Node node) {
    // Get the text before the node and extract the indenting
    Node parent = node.getParentNode();

    String indenting = "";
    NodeList siblingList = parent.getChildNodes();
    for (int i = 1; i < siblingList.getLength(); i++) {
      Node sibling = siblingList.item(i);
      if (sibling == node) {
        Node nodeBefore = siblingList.item(i - 1);
        // Check whether this is a text node
        if (nodeBefore.getNodeName().equals("#text")) {
          // There is text before the node -> Extract the indenting
          String text = nodeBefore.getNodeValue();
          int newlinePos = text.lastIndexOf('\n');
          if (newlinePos != -1) {
            indenting = text.substring(newlinePos);
            if (indenting.trim().length() != 0) {
              // The indenting is no whitespace -> Forget it
              indenting = "";
            }
          }
        }
        break;
      }
    }

    // Now pretty print the node
    prettyPrint(doc, node, indenting);
  }
Example #25
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());
        }
      }
    }
  }
Example #26
0
  @Override
  public boolean hasAttribute(Entity entity, String attribute)
      throws EntityNotFoundException, SchemeException {

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
      dBuilder = dbFactory.newDocumentBuilder();
      Document doc;
      doc = dBuilder.parse(getURL().openStream());
      NodeList nodes = doc.getElementsByTagName("xs:element");
      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        if (element.getAttribute("name").equals(entity.getName())) {
          NodeList childNodes = element.getElementsByTagName("xs:attribute");
          for (int j = 0; j < childNodes.getLength(); j++) {
            element = (Element) childNodes.item(j);
            if (element.getAttribute("name").equals(attribute)) {
              return true;
            }
          }
        }
      }
    } catch (Exception e) {
      throw new SchemeException(e);
    }

    throw new EntityNotFoundException(entity.getName());
  }
  public static void vol(int issue_length, NodeList issue_node) {
    for (int i = 0; i < issue_length; i++) {
      Node nnode = issue_node.item(i);
      if (nnode.getNodeType() == Element.ELEMENT_NODE) {
        Element enode = (Element) nnode;

        NodeList article_node = enode.getElementsByTagName("article");
        int article_length = enode.getElementsByTagName("article").getLength();

        for (int j = 0; j < article_length; j++) {
          Node m = article_node.item(j);
          if (m.getNodeType() == Element.ELEMENT_NODE) {
            Element f = (Element) m;
            String title = f.getElementsByTagName("title").item(0).getTextContent();
            // System.out.println(title);
            if (title.equals("Research in Knowledge Base Management Systems.")) {
              // String article = f.getElementsByTagName("title").item(0).getTextContent();
              String endPage = f.getElementsByTagName("endPage").item(0).getTextContent();
              String initPage = f.getElementsByTagName("initPage").item(0).getTextContent();
              String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent();
              String num_element = enode.getElementsByTagName("number").item(0).getTextContent();
              // System.out.println("Title: "+ title);
              System.out.println("Volume: " + vol_element);
              System.out.println("Number: " + num_element);
              System.out.println("Init Page: " + initPage);
              System.out.println("End Page: " + endPage);
            }
          }
        }
      }
    }
  }
  @Override
  public void loadFromSnapshot(Document doc, Element node) {
    NodeList nl = node.getElementsByTagName("player");
    for (int i = 0; i < nl.getLength(); i++) {
      Element playerEl = (Element) nl.item(i);
      Player player = game.getPlayer(Integer.parseInt(playerEl.getAttribute("index")));
      castles.put(player, Integer.parseInt(playerEl.getAttribute("castles")));
    }

    nl = node.getElementsByTagName("castle");
    for (int i = 0; i < nl.getLength(); i++) {
      Element castleEl = (Element) nl.item(i);
      Position pos = XMLUtils.extractPosition(castleEl);
      Location loc = Location.valueOf(castleEl.getAttribute("location"));
      Castle castle = convertCityToCastle(pos, loc, true);
      boolean isNew = XMLUtils.attributeBoolValue(castleEl, "new");
      boolean isCompleted = XMLUtils.attributeBoolValue(castleEl, "completed");
      if (isNew) {
        newCastles.add(castle);
      } else if (isCompleted) {
        emptyCastles.add(castle);
      } else {
        scoreableCastleVicinity.put(castle, castle.getVicinity());
      }
    }
  }
Example #29
0
  public ArrayList<Entity> getEntitiesFromFile(String filePath) {
    ArrayList<Entity> entities = new ArrayList<>();
    try {
      d = db.parse(filePath);

      NodeList entityMentions = d.getElementsByTagName("entity_mention");
      for (int i = 0; i < entityMentions.getLength(); i++) {
        Element entityMention = (Element) entityMentions.item(i);
        NodeList heads = entityMention.getElementsByTagName("head");
        Element head = (Element) heads.item(0);
        NodeList charseqs = head.getElementsByTagName("charseq");
        Element charseq = (Element) charseqs.item(0);
        int start = Integer.parseInt(charseq.getAttribute("START"));
        int end = Integer.parseInt(charseq.getAttribute("END"));
        String value = charseq.getFirstChild().getNodeValue();
        // value = value.replaceAll("\n", "");
        String id = entityMention.getAttribute("ID");
        Element entityParent = (Element) entityMention.getParentNode();
        String type = entityParent.getAttribute("TYPE");
        // String subType = entityParent.getAttribute("SUBTYPE");
        Entity entity = new Entity(value, start, end, type, id);
        entities.add(entity);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return entities;
  }
  private ArrayList processConsequents(Element rule) {
    NodeList antecedents = rule.getElementsByTagName("consequents");
    ArrayList<String> itemset = new ArrayList();

    if (antecedents != null && antecedents.getLength() > 0) {
      Element antecedent = (Element) antecedents.item(0);

      // Get attributes (items)
      NodeList attributes = antecedent.getElementsByTagName("attribute");
      if (attributes != null && attributes.getLength() > 0) {
        for (int i = 0; i < attributes.getLength(); i++) {
          Element attr = (Element) attributes.item(i);

          String itemId =
              attr.getAttribute("name") + itemNameValueSeparator + attr.getAttribute("value");
          if (!items.containsKey(itemId)) {
            items.put(itemId, itemCounter);
            itemCounter++;
          }
          // Save item to generate itemsets after..
          itemset.add(itemId);
        }
      }
    }

    return itemset;
  }