Ejemplo n.º 1
0
  /**
   * Parses the document using the expected RSS format.
   *
   * @return Feed
   */
  @Override
  public Feed parse(Document document) {
    Feed feed = new Feed();

    // Get the root node.
    Node rssElement = document.getFirstChild();

    NamedNodeMap attrMap = rssElement.getAttributes();
    feed.setVersion(attrMap.getNamedItem("version").getNodeValue());

    // Now get channel.
    NodeList childNodes = rssElement.getChildNodes();
    Node channelNode = null;
    for (int index = 0; index < childNodes.getLength(); index++) {
      Node childNode = childNodes.item(index);

      if (!childNode.getNodeName().equalsIgnoreCase("channel")) {
        continue;
      }

      channelNode = childNode;
    }

    if (channelNode == null) {
      throw new ParserException("Parser could not find the channel element in the RSS feed.");
    }

    // We've done enough here...
    return parseChannel(feed, channelNode);
  }
Ejemplo n.º 2
0
	/** Create a query header from an XML node.
	 *
	 * @param node The &lt;queryAttributes&gt; node.
	 */
	public QueryHeader(Node node) {
		if (!"queryAttributes".equals(node.getNodeName())) {
		  throw new IllegalArgumentException("QueryHeader must be constructed from <queryAttributes> node, not <"
											 + node.getNodeName() + ">");
		}
		NodeList children = node.getChildNodes();
		for (int i = 0; i < children.getLength(); ++i) {
			Node child = children.item(i);
			if ("queryId".equals(child.getNodeName())) {
			  id = XML.unwrappedText(child);
			} else if ("queryTitle".equals(child.getNodeName())) {
			  title = XML.unwrappedText(child);
			} else if ("queryDesc".equals(child.getNodeName())) {
			  description = XML.unwrappedText(child);
			} else if ("queryType".equals(child.getNodeName())) {
			  type = XML.unwrappedText(child);
			} else if ("queryStatusId".equals(child.getNodeName())) {
			  statusID = XML.unwrappedText(child);
			} else if ("querySecurityType".equals(child.getNodeName())) {
			  securityType = XML.unwrappedText(child);
			} else if ("queryParentId".equals(child.getNodeName())) {
			} else if ("queryChildId".equals(child.getNodeName())) {
			} else if ("queryRevisionNote".equals(child.getNodeName())) {
			  revisionNote = XML.unwrappedText(child);
			} else if ("queryDataDictId".equals(child.getNodeName())) {
			  dataDictID = XML.unwrappedText(child);
			}
		}
	}
Ejemplo n.º 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;
  }
  /**
   * Test adding a second md-record to ContentRelation. One md-record already exists.
   *
   * @throws Exception Thrown if adding one md-record failed.
   */
  @Test
  public void testAddMdRecord() throws Exception {

    // add one more md-record
    Document relationCreated = getDocument(relationXml);
    NodeList mdRecordsCreated =
        selectNodeList(relationCreated, "/content-relation/md-records/md-record");
    int numberMdRecordsCreated = mdRecordsCreated.getLength();
    Element mdRecord =
        relationCreated.createElementNS(
            "http://www.escidoc.de/schemas/metadatarecords/0.5",
            "escidocMetadataRecords:md-record");
    mdRecord.setAttribute("name", "md2");
    mdRecord.setAttribute("schema", "bla");
    Element mdRecordContent = relationCreated.createElement("md");
    mdRecord.appendChild(mdRecordContent);
    mdRecordContent.setTextContent("bla");
    selectSingleNode(relationCreated, "/content-relation/md-records").appendChild(mdRecord);
    String relationWithNewMdRecord = toString(relationCreated, false);

    String updatedXml = update(this.relationId, relationWithNewMdRecord);

    // check updated
    assertXmlValidContentRelation(updatedXml);
    Document updatedRelationDocument = getDocument(updatedXml);
    NodeList mdRecordsUpdated =
        selectNodeList(updatedRelationDocument, "/content-relation/md-records/md-record");
    int numberMdRecordsUpdated = mdRecordsUpdated.getLength();
    assertEquals(
        "the content relation should have one additional" + " md-record after update ",
        numberMdRecordsUpdated,
        numberMdRecordsCreated + 1);
  }
Ejemplo n.º 5
0
  /** INTERNAL: */
  public XMLNamedNativeQuery(Node node, XMLHelper helper) {
    // Set the location where we found this query.
    setLocation(helper.getDocumentName());

    // Process the name.
    setName(helper.getNodeValue(node, XMLConstants.ATT_NAME));

    // Process the query string.
    setEJBQLString(helper.getNodeTextValue(node, XMLConstants.QUERY));

    // Process the query hints.
    NodeList hints = helper.getNodes(node, XMLConstants.QUERY_HINT);
    if (hints != null) {
      for (int i = 0; i < hints.getLength(); i++) {
        Node hintNode = hints.item(i);
        String name = helper.getNodeValue(hintNode, XMLConstants.ATT_NAME);
        String value = helper.getNodeValue(hintNode, XMLConstants.ATT_VALUE);
        addHint(new MetadataQueryHint(name, value));
      }
    }

    // Process the result class.
    setResultClass(helper.getNodeValue(node, XMLConstants.ATT_RESULT_CLASS, void.class));

    // Process the result set mapping.
    setResultSetMapping(helper.getNodeValue(node, XMLConstants.ATT_RESULT_SET_MAPPING, ""));
  }
Ejemplo n.º 6
0
 public void init(String path) {
   XmlParser parser = new XmlParser(context);
   Document doc = parser.getDomElement(path);
   Log.d("debugMarcherList", "Got parser and created got the doc");
   Log.d("debugMarcherList", "" + doc);
   // NodeList id = doc.getElementsByTagName(ID);
   // Element el = ( Element ) id.item( 0 );
   // iden = parser.getElementValue(el);
   NodeList nl = doc.getElementsByTagName(DOT);
   Log.d("debugMarcherList", "Got the node list");
   Log.d("debugMarcherList", "" + nl.getLength());
   for (int i = 0; i < nl.getLength(); i++) {
     Element e = (Element) nl.item(i);
     RawDot dot = new RawDot();
     dot.setBpm(Integer.parseInt(parser.getValue(e, BPM)));
     dot.setCount(Integer.parseInt(parser.getValue(e, SETCOUNT)));
     dot.setSide(Integer.parseInt(parser.getValue(e, SIDE)));
     dot.setHorizontal(Integer.parseInt(parser.getValue(e, HORIZONTAL)));
     dot.setHorizontalDirection(parser.getValue(e, HORIZONTALDIRECTION));
     dot.setHorizontalStep(Integer.parseInt(parser.getValue(e, HORIZONTALSTEP)));
     dot.setVertical(parser.getValue(e, VERTICAL));
     dot.setVerticalDir(parser.getValue(e, VERTICALDIRECTION));
     dot.setVerticalStep(Integer.parseInt(parser.getValue(e, VERTICALSTEP)));
     // dotBook.add(dot);
     Log.d("debugMarcherList", "" + dotBook.size());
     Log.d("DotBook", "BPM: " + i + " " + dot.getBPM());
     Log.d("DotBook", "SetCount: " + i + " " + dot.getSetCount());
   }
   Log.d("debugMarcherList", "Done with the init");
 }
Ejemplo n.º 7
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.º 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());
    }
  }
  // the xml is different for these
  protected ArrayList<BGCOffenseSupplementBean> parseSupplements(Element e) {
    // XXX get right element first
    // e = offense
    // supp = offense/recordDetails/recordDetail/supplements (then each /supplement)
    Element eRecordDetails = (Element) e.getElementsByTagName("recordDetails").item(0);
    Element eRecordDetail = (Element) eRecordDetails.getElementsByTagName("recordDetail").item(0);
    Element eSupplements = (Element) eRecordDetail.getElementsByTagName("supplements").item(0);

    // HashMap<String,String> map = new HashMap<String,String>();
    ArrayList<BGCOffenseSupplementBean> list = new ArrayList<BGCOffenseSupplementBean>();
    NodeList nl = eSupplements.getElementsByTagName("supplement");
    for (int i = 0; i < nl.getLength(); i++) {
      Element eSupp = (Element) nl.item(i);
      Node eTitle = eSupp.getFirstChild();
      Node eValue = eSupp.getLastChild();
      if (eTitle.getNodeName().equals("displayTitle")
          && eValue.getNodeName().equals("displayValue")) {
        String sTitle = eTitle.getFirstChild().getNodeValue(); // getTextContent();
        String sValue = eValue.getFirstChild().getNodeValue(); // getTextContent();
        BGCOffenseSupplementBean bean = new BGCOffenseSupplementBean();
        bean.setDisplayTitle(sTitle);
        bean.setDisplayValue(sValue);
        // map.put(sTitle, sValue);
        list.add(bean);
      }
    }
    // return map;
    return list;
  }
Ejemplo n.º 10
0
  /**
   * Constructs a new text element for a specified node element
   *
   * @param treeRepresentation tree representation
   * @param element SVG element
   */
  public TextElement(
      TreeRepresentation treeRepresentation, NodeElement nodeElement, AbstractElement element) {
    super(treeRepresentation, element);
    this.treeRepresentation = treeRepresentation;
    this.nodeElement = nodeElement;

    // text span vector
    tspanVector = new Vector<TSpanElement>();
    NodeList nodeList = element.getElementsByTagName("tspan");
    for (int i = 0; i < nodeList.getLength(); i++) {
      AbstractElement childElement = (AbstractElement) nodeList.item(i);
      tspanVector.add(new TSpanElement(treeRepresentation, childElement));
    }

    // alignment
    String alignment = element.getAttribute("alignment");
    if (alignment.compareTo(ALIGN_LEFT) == 0) setAlignment(ALIGN_LEFT);
    if (alignment.compareTo(ALIGN_CENTER) == 0) setAlignment(ALIGN_CENTER);
    if (alignment.compareTo(ALIGN_RIGHT) == 0) setAlignment(ALIGN_RIGHT);

    // visible
    String visible = element.getAttribute("visibility");
    if (visible.compareTo(VISIBLE) == 0) setVisible(true);
    if (visible.compareTo(INVISIBLE) == 0) setVisible(false);

    setTaintMode(TAINTED);
  }
  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
 private void xmlReadSelectedElements(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("selectedElements")) { // $NON-NLS-1$
     jarPackage.setExportClassFiles(
         getBooleanAttribute(element, "exportClassFiles")); // $NON-NLS-1$
     jarPackage.setExportOutputFolders(
         getBooleanAttribute(element, "exportOutputFolder", false)); // $NON-NLS-1$
     jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); // $NON-NLS-1$
     NodeList selectedElements = element.getChildNodes();
     Set<IAdaptable> elementsToExport = new HashSet<IAdaptable>(selectedElements.getLength());
     for (int j = 0; j < selectedElements.getLength(); j++) {
       Node selectedNode = selectedElements.item(j);
       if (selectedNode.getNodeType() != Node.ELEMENT_NODE) continue;
       Element selectedElement = (Element) selectedNode;
       if (selectedElement.getNodeName().equals("file")) // $NON-NLS-1$
       addFile(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("folder")) // $NON-NLS-1$
       addFolder(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("project")) // $NON-NLS-1$
       addProject(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("javaElement")) // $NON-NLS-1$
       addJavaElement(elementsToExport, selectedElement);
       // Note: Other file types are not handled by this writer
     }
     jarPackage.setElements(elementsToExport.toArray());
   }
 }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
0
  /**
   * Get container window
   *
   * <p>
   *
   * @return String
   */
  private String getWindowName(String sWidgetID) {

    String sWindowName = null;
    // get widget ID
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    Object result;
    NodeList nodes;
    try {
      String xpathExpression =
          "/GUIStructure/GUI[Container//Property[Name=\""
              + GUITARConstants.ID_TAG_NAME
              + "\" and Value=\""
              + sWidgetID
              + "\"]]/Window/Attributes/Property[Name=\""
              + GUITARConstants.TITLE_TAG_NAME
              + "\"]/Value/text()";
      expr = xpath.compile(xpathExpression);
      result = expr.evaluate(docGUI, XPathConstants.NODESET);
      nodes = (NodeList) result;
      if (nodes.getLength() > 0) sWindowName = nodes.item(0).getNodeValue();
    } catch (XPathExpressionException e) {
      GUITARLog.log.error(e);
    }
    return sWindowName;
  }
  public IXArchElement cloneElement(int depth) {
    synchronized (DOMUtils.getDOMLock(elt)) {
      Document doc = elt.getOwnerDocument();
      if (depth == 0) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      } else if (depth == 1) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());

        NodeList nl = elt.getChildNodes();
        int size = nl.getLength();
        for (int i = 0; i < size; i++) {
          Node n = nl.item(i);
          Node cloneNode = (Node) n.cloneNode(false);
          cloneNode = doc.importNode(cloneNode, true);
          cloneElt.appendChild(cloneNode);
        }
        return cloneImpl;
      } else /* depth = infinity */ {
        Element cloneElt = (Element) elt.cloneNode(true);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      }
    }
  }
 /**
  * Helper method to find a specific element within a root element or to create that element if it
  * does not exist.
  */
 public Element getElement(Element parent, SammaXml.ELEMENT tag) {
   NodeList nl = parent.getElementsByTagName(tag.toString());
   if (nl.getLength() == 1) return (Element) nl.item(0);
   Element newel = parent.getOwnerDocument().createElement(tag.toString());
   parent.appendChild(newel);
   return newel;
 }
Ejemplo n.º 17
0
  protected static void trimEmptyTextNodes(Node node) {
    Element element = null;
    if (node instanceof Document) {
      element = ((Document) node).getDocumentElement();
    } else if (node instanceof Element) {
      element = (Element) node;
    } else {
      return;
    }

    List<Node> nodesToRemove = new ArrayList<Node>();
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      Node child = children.item(i);
      if (child instanceof Element) {
        trimEmptyTextNodes(child);
      } else if (child instanceof Text) {
        Text t = (Text) child;
        if (t.getData().trim().length() == 0) {
          nodesToRemove.add(child);
        }
      }
    }

    for (Node n : nodesToRemove) {
      element.removeChild(n);
    }
  }
Ejemplo n.º 18
0
  public void readHelper(org.w3c.dom.Element docElement) {

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

    if (docElement.getNodeName().equals("urls")) {
      // System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
      // NodeList nList = doc.getElementsByTagName("service");

      NodeList nList = docElement.getChildNodes();

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

        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode;

          // System.out.println(eElement.getTextContent());
          String url = eElement.getTextContent();
          if (this.urls == null) {
            this.urls = new ArrayList<String>();
          }
          this.urls.add(url);
        }
      }
    }
  }
Ejemplo n.º 19
0
 /**
  * @param nodeList
  * @return
  */
 private static Stream<Node> streamNodes(NodeList nodeList) {
   final List<Node> nodes = new ArrayList<>();
   for (int i = 0, to = nodeList.getLength(); i < to; i++) {
     nodes.add(nodeList.item(i));
   }
   return nodes.stream();
 }
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;
 }
 /** 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;
 }
Ejemplo n.º 22
0
  public VOMSWarningMessage[] warningMessages() {

    NodeList nodes = xmlResponse.getElementsByTagName("item");

    if (nodes.getLength() == 0) return null;

    List<VOMSWarningMessage> warningList = new ArrayList<VOMSWarningMessage>();

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

      Element itemElement = (Element) nodes.item(i);

      Element numberElement = (Element) itemElement.getElementsByTagName("number").item(0);
      Element messageElement = (Element) itemElement.getElementsByTagName("message").item(0);

      int number = Integer.parseInt(numberElement.getFirstChild().getNodeValue());

      if (number < ERROR_OFFSET)
        warningList.add(
            new VOMSWarningMessage(number, messageElement.getFirstChild().getNodeValue()));
    }

    if (warningList.isEmpty()) return null;

    return warningList.toArray(new VOMSWarningMessage[warningList.size()]);
  }
Ejemplo n.º 23
0
 private String nodeToString(final Element elem) {
   final StringBuffer stringBuffer = new StringBuffer();
   stringBuffer.append(Constants.LESS_THAN).append(elem.getNodeName());
   final NamedNodeMap namedNodeMap = elem.getAttributes();
   for (int i = 0; i < namedNodeMap.getLength(); i++) {
     stringBuffer
         .append(Constants.STRING_BLANK)
         .append(namedNodeMap.item(i).getNodeName())
         .append(Constants.EQUAL)
         .append(Constants.QUOTATION + namedNodeMap.item(i).getNodeValue() + Constants.QUOTATION);
   }
   stringBuffer.append(Constants.GREATER_THAN);
   final NodeList nodeList = elem.getChildNodes();
   for (int i = 0; i < nodeList.getLength(); i++) {
     final Node node = nodeList.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       // If the type of current node is ELEMENT_NODE, process it
       stringBuffer.append(nodeToString((Element) node));
     }
     if (node.getNodeType() == Node.TEXT_NODE) {
       stringBuffer.append(node.getNodeValue());
     }
   }
   stringBuffer.append("</").append(elem.getNodeName()).append(Constants.GREATER_THAN);
   return stringBuffer.toString();
 }
  /**
   * 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);
  }
Ejemplo n.º 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());
        }
      }
    }
  }
 public KalturaUrlTokenizerAkamaiSecureHd(Element node) throws KalturaApiException {
   super(node);
   NodeList childNodes = node.getChildNodes();
   for (int i = 0; i < childNodes.getLength(); i++) {
     Node aNode = childNodes.item(i);
     String nodeName = aNode.getNodeName();
     String txt = aNode.getTextContent();
     if (nodeName.equals("paramName")) {
       this.paramName = ParseUtils.parseString(txt);
       continue;
     } else if (nodeName.equals("aclPostfix")) {
       this.aclPostfix = ParseUtils.parseString(txt);
       continue;
     } else if (nodeName.equals("customPostfixes")) {
       this.customPostfixes = ParseUtils.parseString(txt);
       continue;
     } else if (nodeName.equals("useCookieHosts")) {
       this.useCookieHosts = ParseUtils.parseString(txt);
       continue;
     } else if (nodeName.equals("rootDir")) {
       this.rootDir = ParseUtils.parseString(txt);
       continue;
     }
   }
 }
Ejemplo n.º 27
0
  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);
            }
          }
        }
      }
    }
  }
  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);
  }
  public OptionSelectionDetailsType(Node node) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Node childNode = null;
    NodeList nodeList = null;
    childNode = (Node) xpath.evaluate("OptionSelection", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.optionSelection = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("Price", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.price = childNode.getTextContent();
    }

    childNode = (Node) xpath.evaluate("OptionType", node, XPathConstants.NODE);
    if (childNode != null && !isWhitespaceNode(childNode)) {
      this.optionType = OptionTypeListType.fromValue(childNode.getTextContent());
    }
    nodeList = (NodeList) xpath.evaluate("PaymentPeriod", node, XPathConstants.NODESET);
    if (nodeList != null && nodeList.getLength() > 0) {
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node subNode = nodeList.item(i);
        this.paymentPeriod.add(new InstallmentDetailsType(subNode));
      }
    }
  }
Ejemplo n.º 30
0
  private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);
      String namespace = attribute.getNamespaceURI();

      if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {
        try {
          namespaceSources.add(new URI(attribute.getValue()));
        } catch (URISyntaxException e) {
          throw new SAXException(
              "Cannot validate this document with this class.  Namespaces must be valid URIs.  Found Namespace: '"
                  + attribute.getValue()
                  + "'.",
              e);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    int childCount = childNodes.getLength();
    for (int i = 0; i < childCount; i++) {
      Node child = childNodes.item(i);

      if (child.getNodeType() == Node.ELEMENT_NODE) {
        gatherNamespaces((Element) child, namespaceSources);
      }
    }
  }