コード例 #1
0
ファイル: PeakMLParser.java プロジェクト: joewandy/HDP-Align
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getFirstChild();

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null)
            throw new XmlParserException("Failed to locate the type attribute.");
          if (!typeattribute.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
            throw new XmlParserException(
                "IPeak ("
                    + typeattribute.getNodeValue()
                    + ") is not of type: '"
                    + PeakMLWriter.TYPE_BACKGROUNDION
                    + "'");

          // parse this node as a mass chromatogram
          BackgroundIon<? extends Peak> backgroundion = parseBackgroundIon(node);
          if (backgroundion != null) peaks.add(backgroundion);

          //
          if (_listener != null && result.header != null && result.header.getNrPeaks() != 0)
            _listener.update((100. * index++) / result.header.getNrPeaks());
        } else if (xpath.equals(XPATH_HEADER)) {
          result.header = parseHeader(document.getFirstChild());
        }
      }
コード例 #2
0
  private static void process(Document document, Document document2) {
    final Node root1 = document.getFirstChild();
    final Node root2 = document2.getFirstChild();

    fillListFromChildren(attributeList1, root1);
    fillListFromChildren(attributeList2, root2);

    compareLists(attributeList1, attributeList2);
  }
コード例 #3
0
ファイル: AtomTypeFactoryTest.java プロジェクト: jonalv/cdk
  @Test
  public void testCanReadCMLSchema() throws Exception {
    InputStream cmlSchema = new FileInputStream(tmpCMLSchema);
    Assert.assertNotNull("Could not find the CML schema", cmlSchema);

    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    // make sure the schema is read
    Document schemaDoc = parser.parse(cmlSchema);
    Assert.assertNotNull(schemaDoc.getFirstChild());
    Assert.assertEquals("xsd:schema", schemaDoc.getFirstChild().getNodeName());
  }
コード例 #4
0
  public ViewFragment showBean(
      BeanType bean,
      HttpServletRequest req,
      UserType user,
      URIParser uriParser,
      ValidationError validationError,
      FormCallback formCallback)
      throws Exception {

    log.info("User " + user + " viewing " + this.typeLogName + " " + bean);

    Document doc = createDocument(req, uriParser, user);
    Element showTypeElement = doc.createElement("Show" + typeElementName);
    doc.getFirstChild().appendChild(showTypeElement);

    this.appendBean(bean, showTypeElement, doc);

    this.appendShowFormData(bean, doc, showTypeElement, user, req, uriParser, formCallback);

    if (validationError != null) {
      showTypeElement.appendChild(validationError.toXML(doc));
      showTypeElement.appendChild(RequestUtils.getRequestParameters(req, doc));
    }

    return createViewFragment(doc);
  }
コード例 #5
0
ファイル: XmlMetadataReader.java プロジェクト: jrjm/ffpojo
  public Map<Class<?>, RecordDescriptor> readMetadata() throws MetadataReaderException {
    InputStream schemaFileInputStream =
        getClass().getClassLoader().getResourceAsStream(SCHEMA_CLASSPATH);

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setAttribute(
        ATTRIBUTE_JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
    docBuilderFactory.setAttribute(ATTRIBUTE_JAXP_SCHEMA_SOURCE, schemaFileInputStream);
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setNamespaceAware(true);
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setCoalescing(true);
    docBuilderFactory.setIgnoringElementContentWhitespace(true);

    Document doc;
    try {
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      docBuilder.setErrorHandler(new XmlValidationErrorHandler());
      doc = docBuilder.parse(xmlMetadataInputStream);
    } catch (ParserConfigurationException e) {
      throw new MetadataReaderException(e);
    } catch (IOException e) {
      throw new MetadataReaderException(e);
    } catch (SAXException e) {
      throw new MetadataReaderException(e);
    }

    Node rootNode = doc.getFirstChild();

    return readFFPojoMappingsNode(rootNode);
  }
コード例 #6
0
ファイル: FileHandler.java プロジェクト: 6/CS-Projects
  /**
   * Loads a given XML file and returns a list of its SoundResources.
   *
   * @param filePath location of XML file to load.
   * @return list of SoundResources
   * @throws IOException when an I/O error occurs
   * @throws SAXException when an XML parsing error is encountered
   */
  public List<SoundResource> loadFromFile(String filePath) throws SAXException, IOException {
    FileInputStream stream = new FileInputStream(filePath);
    Document document = docBuilder.parse(stream);

    // get all child sounds, start at the root node from the Document
    return getSoundResources(document.getFirstChild().getChildNodes());
  }
コード例 #7
0
 /**
  * Update an application in the manifest
  *
  * @param app app to replace for
  */
 public void updateApplication(PhoneLabApplication app) {
   try {
     Node node =
         (Node)
             xpath.evaluate(
                 "/manifest/statusmonitor/parameter[@package_name='" + app.getPackageName() + "']",
                 document,
                 XPathConstants.NODE);
     if (node != null) { // exist
       Node parentNode = node.getParentNode();
       parentNode.removeChild(node);
       Element newElement = document.createElement("application");
       if (app.getPackageName() != null)
         newElement.setAttribute("package_name", app.getPackageName());
       if (app.getName() != null) newElement.setAttribute("name", app.getName());
       if (app.getDescription() != null)
         newElement.setAttribute("description", app.getDescription());
       if (app.getType() != null) newElement.setAttribute("type", app.getType());
       if (app.getStartTime() != null) newElement.setAttribute("start_time", app.getStartTime());
       if (app.getEndTime() != null) newElement.setAttribute("end_time", app.getEndTime());
       if (app.getDownload() != null) newElement.setAttribute("download", app.getDownload());
       if (app.getVersion() != null) newElement.setAttribute("version", app.getVersion());
       if (app.getAction() != null) newElement.setAttribute("action", app.getAction());
       document.getFirstChild().appendChild(newElement);
     }
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
 }
コード例 #8
0
 public void testUpdateSequenceInferiorGet() throws Exception {
   Document dom = getAsDOM(BASEPATH + "?request=GetCapabilities&service=WCS&updateSequence=-1");
   checkValidationErrors(dom, WCS10_GETCAPABILITIES_SCHEMA);
   final Node root = dom.getFirstChild();
   assertEquals("wcs:WCS_Capabilities", root.getNodeName());
   assertTrue(root.getChildNodes().getLength() > 0);
 }
コード例 #9
0
 /**
  * Extracts a URL from a document that consists of a URL only.
  *
  * @param doc
  * @return the URL
  */
 protected URL extractURL(Document doc) throws IOException {
   if (doc == null) {
     return null;
   }
   String url = doc.getFirstChild().getTextContent();
   return (null == url || "".equals(url)) ? null : new URL(url);
 }
コード例 #10
0
  public void testAnnotations() {

    SwingAppFrameworkInspector inspector = new SwingAppFrameworkInspector();

    Document document = XmlUtils.documentFromString(inspector.inspect(null, Foo.class.getName()));

    assertEquals("inspection-result", document.getFirstChild().getNodeName());

    // Entity

    Element entity = (Element) document.getDocumentElement().getFirstChild();
    assertEquals(ENTITY, entity.getNodeName());
    assertEquals(Foo.class.getName(), entity.getAttribute(TYPE));
    assertFalse(entity.hasAttribute(NAME));

    // Actions

    Element action = (Element) entity.getFirstChild();
    assertEquals(ACTION, action.getNodeName());
    assertEquals("doBar", action.getAttribute(NAME));
    assertEquals("barLabel", action.getAttribute(LABEL));
    assertEquals(action.getAttributes().getLength(), 2);

    assertEquals(entity.getChildNodes().getLength(), 1);
  }
コード例 #11
0
ファイル: MultisellData.java プロジェクト: ailian8415/l2mx
  @Override
  public void parseDocument(Document doc, File f) {
    try {
      int id = Integer.parseInt(f.getName().replaceAll(".xml", ""));
      int entryId = 1;
      Node att;
      final ListContainer list = new ListContainer(id);

      for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
          att = n.getAttributes().getNamedItem("applyTaxes");
          list.setApplyTaxes((att != null) && Boolean.parseBoolean(att.getNodeValue()));

          att = n.getAttributes().getNamedItem("useRate");
          if (att != null) {
            try {

              list.setUseRate(Double.valueOf(att.getNodeValue()));
              if (list.getUseRate() <= 1e-6) {
                throw new NumberFormatException(
                    "The value cannot be 0"); // threat 0 as invalid value
              }
            } catch (NumberFormatException e) {
              try {
                list.setUseRate(Config.class.getField(att.getNodeValue()).getDouble(Config.class));
              } catch (Exception e1) {
                LOG.warn(
                    "{}: Unable to parse {}", getClass().getSimpleName(), doc.getLocalName(), e1);
                list.setUseRate(1.0);
              }

            } catch (DOMException e) {
              LOG.warn("{}: Unable to parse {}", getClass().getSimpleName(), doc.getLocalName(), e);
            }
          }

          att = n.getAttributes().getNamedItem("maintainEnchantment");
          list.setMaintainEnchantment((att != null) && Boolean.parseBoolean(att.getNodeValue()));

          for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
            if ("item".equalsIgnoreCase(d.getNodeName())) {
              Entry e = parseEntry(d, entryId++, list);
              list.getEntries().add(e);
            } else if ("npcs".equalsIgnoreCase(d.getNodeName())) {
              for (Node b = d.getFirstChild(); b != null; b = b.getNextSibling()) {
                if ("npc".equalsIgnoreCase(b.getNodeName())) {
                  if (Util.isDigit(b.getTextContent())) {
                    list.allowNpc(Integer.parseInt(b.getTextContent()));
                  }
                }
              }
            }
          }
        }
      }
      _entries.put(id, list);
    } catch (Exception e) {
      LOG.error("{}: Error in file {}", getClass().getSimpleName(), f, e);
    }
  }
コード例 #12
0
  private void bindContext(Context context, List<ConfigInput> inputs) {
    final XmlUtil xmlUtil = new XmlUtil();
    Document document = null;
    for (ConfigInput input : inputs) {
      try {
        if (input.getSource() != null) {
          if (input.getSource().startsWith("file:")) {
            File file = new File(input.getSource().replaceFirst("file:", ""));
            document = xmlUtil.getDocument(file);
          } else if (input.getSource().startsWith("http://")) {
            IOUtil ioUtil = new IOUtil();
            InputStream inputStream = ioUtil.getContent(input.getSource());
            document = xmlUtil.getDocument(inputStream);
          } else if (input.getSource().startsWith("classpath:")) {
            URL url =
                this.getClass()
                    .getClassLoader()
                    .getResource(input.getSource().replaceFirst("classpath:", ""));
            File file = new File(url.getPath());
            document = xmlUtil.getDocument(file);
          }
        }

        if (document != null) {
          context.put(input.getId(), new XmlTool(document.getFirstChild()));
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #13
0
ファイル: RssParser.java プロジェクト: ianaldrighetti/jFR
  /**
   * 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);
  }
コード例 #14
0
  public ViewFragment showUpdateForm(
      BeanType bean,
      HttpServletRequest req,
      UserType user,
      URIParser uriParser,
      ValidationException validationException,
      FormCallback formCallback)
      throws Exception {

    log.info("User " + user + " requested update " + this.typeLogName + " form for " + bean);

    Document doc = createDocument(req, uriParser, user);
    Element updateTypeElement = doc.createElement("Update" + typeElementName);
    doc.getFirstChild().appendChild(updateTypeElement);

    appendBean(bean, updateTypeElement, doc);

    if (validationException != null) {
      updateTypeElement.appendChild(validationException.toXML(doc));
      updateTypeElement.appendChild(RequestUtils.getRequestParameters(req, doc));
    }

    this.appendUpdateFormData(bean, doc, updateTypeElement, user, req, uriParser, formCallback);

    return createViewFragment(doc);
  }
コード例 #15
0
  /**
   * Constructor
   *
   * @param filename the XML config file
   */
  public LdapConfig(String filename) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(filename);

    // -- root element
    Node node = document.getFirstChild();
    while (node != null && node.getNodeType() != Node.ELEMENT_NODE) node = node.getNextSibling();

    if (node == null || !node.getNodeName().equals("ldap"))
      throw new Exception("root element is different from 'ldap'");

    this.ldapUrl = node.getAttributes().getNamedItem("url").getNodeValue();

    node = node.getFirstChild();
    while (node != null) {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNodeName().equals("authentication")) handleAuthentication(node);
        else if (node.getNodeName().equals("plugins")) handlePlugins(node);
        else if (node.getNodeName().equals("services")) handleServices(node);
        else if (node.getNodeName().equals("users")) handleUsers(node);
        else if (node.getNodeName().equals("groups")) handleGroups(node);
        else Logging.getLogger().warning("unexepected node : " + node.getNodeName());
      }
      node = node.getNextSibling();
    }
  }
コード例 #16
0
  public User getById(long id) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    User u = new User();

    try {

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

      // parse using builder to get DOM representation of the XML file
      Document dom = db.parse(xmlPath + "/" + id + ".xml");
      Node rootNode = dom.getFirstChild();

      for (int i = 0; i < rootNode.getChildNodes().getLength(); i++) {
        Node p = rootNode.getChildNodes().item(i);

        if (p.getNodeName().equals("name")) u.name = p.getTextContent();
        if (p.getNodeName().equals("id")) u.id = Long.parseLong(p.getTextContent());
      }

    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (SAXException se) {
      se.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }

    return u;
  }
コード例 #17
0
  private void load() {
    try {
      File f = new File("./data/xml/admin_commands_rights.xml");
      Document doc = XMLDocumentFactory.getInstance().loadDocument(f);

      Node n = doc.getFirstChild();
      for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
        if (d.getNodeName().equalsIgnoreCase("aCar")) {
          NamedNodeMap attrs = d.getAttributes();

          String adminCommand = attrs.getNamedItem("name").getNodeValue();
          String accessLevels = attrs.getNamedItem("accessLevel").getNodeValue();
          _adminCommandAccessRights.put(
              adminCommand, new L2AdminCommandAccessRight(adminCommand, accessLevels));
        }
      }
    } catch (Exception e) {
      _log.log(
          Level.WARNING,
          "AdminCommandAccessRights: Error loading from database:" + e.getMessage(),
          e);
    }

    _log.info(
        "AdminCommandAccessRights: Loaded "
            + _adminCommandAccessRights.size()
            + " commands accesses' rights.");
  }
コード例 #18
0
 /**
  * Clones the document parameter and appends the result to the given parent node.
  *
  * @param parentNode The node to append the document to.
  * @param doc The document to be appended.
  */
 private void appendXMLStructureToNode(Element parentNode, Document doc) {
   if (doc != null) {
     Node cloneNode = doc.getFirstChild().cloneNode(true);
     cloneNode = parentNode.getOwnerDocument().importNode(cloneNode, true);
     parentNode.appendChild(cloneNode);
   }
 }
コード例 #19
0
ファイル: DBGpResponse.java プロジェクト: eclipse/pdt
  private void parseResponse(InputStream is) {
    id = null;
    command = null;
    type = UNKNOWN_TYPE;
    errorCode = ERROR_UNKNOWN_TYPE;

    try {
      doc = db.parse(is);
      parent = doc.getFirstChild();
      String nodeName = parent.getNodeName();
      if (nodeName.equals("response")) { // $NON-NLS-1$
        parseResponseType();
      } else if (nodeName.equals("init")) { // $NON-NLS-1$
        parseInitType();
      } else if (nodeName.equals("stream")) { // $NON-NLS-1$
        parseStreamType();
      } else if (nodeName.equals("proxyinit")) { // $NON-NLS-1$
        parseProxyInitType();
      } else if (nodeName.equals("proxyerror")) { // $NON-NLS-1$
        parseProxyErrorType();
      }

    } catch (SAXException e) {
      DBGpLogger.logException(null, this, e);
      type = PARSE_FAILURE;
      errorCode = ERROR_PARSE_FAILURE;
    } catch (IOException e) {
      DBGpLogger.logException(null, this, e);
      type = PARSE_FAILURE;
      errorCode = ERROR_PARSE_FAILURE;
    }
    // System.out.println("wait for me");
  }
コード例 #20
0
 static {
   try {
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
     Document document = dbBuilder.parse(PROPERTIES_FILE_PATH);
     Node root = document.getFirstChild();
     if (root != null && "properties".equals(root.getNodeName())) {
       NodeList childNodes = root.getChildNodes();
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node node = childNodes.item(i);
         if ("property".equals(node.getNodeName())) {
           NamedNodeMap attributes = node.getAttributes();
           Node keyNode = attributes.getNamedItem("key");
           Node valueNode = attributes.getNamedItem("value");
           if (keyNode != null && valueNode != null) {
             String key = keyNode.getNodeValue();
             String value = valueNode.getNodeValue();
             if (key != null && !key.isEmpty() && value != null && !value.isEmpty()) {
               PROPERTIES_FILE.put(key, value);
             }
           }
         }
       }
     }
   } catch (ParserConfigurationException | SAXException | IOException ex) {
   }
 }
コード例 #21
0
ファイル: Ranking.java プロジェクト: EternalBane/Asteroid
  private void xmlWrite(String name, String score) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      docFactory.setValidating(true);
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      org.w3c.dom.Document doc = docBuilder.parse(xml);

      Node data = doc.getFirstChild();

      org.w3c.dom.Element root = doc.createElement("ranking");
      org.w3c.dom.Element player = doc.createElement("player");
      org.w3c.dom.Element _name = doc.createElement("name");
      _name.setTextContent(name);
      org.w3c.dom.Element _score = doc.createElement("score");
      _score.setTextContent(score);

      player.appendChild(_name);
      player.appendChild(_score);
      root.appendChild(player);

      data.appendChild(player);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(xml);
      transformer.transform(source, result);

    } catch (Exception ex) {
    }
  }
コード例 #22
0
  public void updateList(String fileName, int corridorSize) {
    tilesToDownload.clear();
    File file = new File(fileName);
    if (file.exists() && file.isFile()) {
      try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(file);

        Node gpxNode = document.getFirstChild();
        if (!gpxNode.getNodeName().equalsIgnoreCase("gpx")) {
          throw new RuntimeException("invalid file!");
        }

        // Object result = expr.evaluate(document, XPathConstants.NODESET);
        // NodeList nodes = (NodeList) result;
        NodeList nodes = gpxNode.getChildNodes();
        int detectedTrackNumber = 0;
        for (int i = 0; i < nodes.getLength(); i++) {
          if (nodes.item(i).getLocalName() != null
              && nodes.item(i).getLocalName().equalsIgnoreCase("trk")) {
            detectedTrackNumber++;
            // if (detectedTrackNumber == 1) {
            // Download all zoomlevels
            for (int zoomLevel : getDownloadZoomLevels()) {
              // handle all trgSegments
              NodeList trkSegs = nodes.item(i).getChildNodes();
              for (int indexTrkSeg = 0; indexTrkSeg < trkSegs.getLength(); indexTrkSeg++) {
                if (trkSegs.item(indexTrkSeg).getLocalName() != null
                    && trkSegs.item(indexTrkSeg).getLocalName().equalsIgnoreCase("trkseg")) {
                  // handle all trkpts
                  NodeList trkPts = trkSegs.item(indexTrkSeg).getChildNodes();
                  for (int indexTrkPt = 0; indexTrkPt < trkPts.getLength(); indexTrkPt++) {
                    if (trkPts.item(indexTrkPt).getLocalName() != null
                        && trkPts.item(indexTrkPt).getLocalName().equalsIgnoreCase("trkpt")) {
                      handleTrkPt(trkPts.item(indexTrkPt), zoomLevel, corridorSize);
                    }
                  }
                }
              }
            }
            // }
          }
        }
      } catch (SAXParseException spe) {
        Exception e = (spe.getException() != null) ? spe.getException() : spe;
        log.log(
            Level.SEVERE, "Error parsing " + spe.getSystemId() + " line " + spe.getLineNumber(), e);
      } catch (SAXException sxe) {
        Exception e = (sxe.getException() != null) ? sxe.getException() : sxe;
        log.log(Level.SEVERE, "Error parsing GPX", e);
      } catch (ParserConfigurationException pce) {
        log.log(Level.SEVERE, "Error in parser configuration", pce);
      } catch (IOException ioe) {
        log.log(Level.SEVERE, "Error parsing GPX", ioe);
      }
    }
  }
コード例 #23
0
ファイル: VoteManager.java プロジェクト: Hl4p3x/mobius-source
  /** Method load. */
  public static void load() {
    VoteList.clear();

    try {
      File file = new File(Config.DATAPACK_ROOT, "data/xml/other/vote.xml");
      DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
      factory2.setValidating(false);
      factory2.setIgnoringComments(true);
      Document doc2 = factory2.newDocumentBuilder().parse(file);

      for (Node n2 = doc2.getFirstChild(); n2 != null; n2 = n2.getNextSibling()) {
        if ("list".equals(n2.getNodeName())) {
          for (Node d2 = n2.getFirstChild(); d2 != null; d2 = d2.getNextSibling()) {
            if ("vote".equals(d2.getNodeName())) {
              Vote v = new Vote();
              v.id = Integer.parseInt(d2.getAttributes().getNamedItem("id").getNodeValue());
              v.maxPerAccount =
                  Integer.parseInt(d2.getAttributes().getNamedItem("maxPerAccount").getNodeValue());
              v.name = d2.getAttributes().getNamedItem("name").getNodeValue();
              v.active =
                  Boolean.parseBoolean(d2.getAttributes().getNamedItem("active").getNodeValue());

              for (Node i = d2.getFirstChild(); i != null; i = i.getNextSibling()) {
                if ("variant".equals(i.getNodeName())) {
                  v.variants.put(
                      Integer.parseInt(i.getAttributes().getNamedItem("id").getNodeValue()),
                      i.getAttributes().getNamedItem("desc").getNodeValue());
                }
              }

              VoteList.put(v.id, v);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    try (Connection con = DatabaseFactory.getInstance().getConnection(); ) {

      PreparedStatement st = con.prepareStatement("SELECT * FROM vote");
      ResultSet rs = st.executeQuery();

      while (rs.next()) {
        Vote v = VoteList.get(rs.getInt("id"));

        if (v != null) {
          String HWID = rs.getString("HWID");
          Integer[] rez = v.results.get(HWID);
          v.results.put(HWID, ArrayUtils.add(rez, rs.getInt("vote")));
        }
      }
      rs.close();
      st.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #24
0
 /**
  * This constructor parses the document and stores all namespaces it can find. If toplevelOnly is
  * true, only namespaces in the root are used.
  *
  * @param document source document
  * @param toplevelOnly restriction of the search to enhance performance
  */
 public NamespaceResolver(Document document, boolean toplevelOnly) {
   examineNode(document.getFirstChild(), toplevelOnly);
   //   System.out.println("The list of the cached namespaces:");
   //   for (String key : prefix2Uri.keySet()) {
   //       System.out
   //               .println("prefix " + key + ": uri " + prefix2Uri.get(key));
   //   }
 }
コード例 #25
0
 public void setUp() throws Exception {
   XMLUnit.setIgnoreWhitespace(true);
   final Document assertionDoc =
       DocumentUtil.getDocument(getClass().getResourceAsStream("/wstrust/assertion.xml"));
   assertionElement = (Element) assertionDoc.getFirstChild();
   expectedAssertion =
       new InputSource(getClass().getResourceAsStream("/wstrust/assertion-expected.xml"));
 }
コード例 #26
0
  /**
   * Sign a node in a document
   *
   * @param doc
   * @param nodeToBeSigned
   * @param keyPair
   * @param publicKey
   * @param digestMethod
   * @param signatureMethod
   * @param referenceURI
   * @return
   * @throws ParserConfigurationException
   * @throws XMLSignatureException
   * @throws MarshalException
   * @throws GeneralSecurityException
   */
  public static Document sign(
      Document doc,
      Node nodeToBeSigned,
      KeyPair keyPair,
      String digestMethod,
      String signatureMethod,
      String referenceURI,
      X509Certificate x509Certificate)
      throws ParserConfigurationException, GeneralSecurityException, MarshalException,
          XMLSignatureException {
    if (nodeToBeSigned == null) throw logger.nullArgumentError("Node to be signed");

    if (logger.isTraceEnabled()) {
      logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }

    Node parentNode = nodeToBeSigned.getParentNode();

    // Let us create a new Document
    Document newDoc = DocumentUtil.createDocument();
    // Import the node
    Node signingNode = newDoc.importNode(nodeToBeSigned, true);
    newDoc.appendChild(signingNode);

    if (!referenceURI.isEmpty()) {
      propagateIDAttributeSetup(nodeToBeSigned, newDoc.getDocumentElement());
    }
    newDoc = sign(newDoc, keyPair, digestMethod, signatureMethod, referenceURI, x509Certificate);

    // if the signed element is a SAMLv2.0 assertion we need to move the signature element to the
    // position
    // specified in the schema (before the assertion subject element).
    if (nodeToBeSigned.getLocalName().equals("Assertion")
        && WSTrustConstants.SAML2_ASSERTION_NS.equals(nodeToBeSigned.getNamespaceURI())) {
      Node signatureNode =
          DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.DSIG_NS, "Signature"));
      Node subjectNode =
          DocumentUtil.getElement(
              newDoc, new QName(WSTrustConstants.SAML2_ASSERTION_NS, "Subject"));
      if (signatureNode != null && subjectNode != null) {
        newDoc.getDocumentElement().removeChild(signatureNode);
        newDoc.getDocumentElement().insertBefore(signatureNode, subjectNode);
      }
    }

    // Now let us import this signed doc into the original document we got in the method call
    Node signedNode = doc.importNode(newDoc.getFirstChild(), true);

    if (!referenceURI.isEmpty()) {
      propagateIDAttributeSetup(newDoc.getDocumentElement(), (Element) signedNode);
    }

    parentNode.replaceChild(signedNode, nodeToBeSigned);
    // doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);

    return doc;
  }
コード例 #27
0
 @Override
 protected void parse(Document doc) {
   for (Node list = doc.getFirstChild(); list != null; list = list.getNextSibling())
     if ("list".equals(list.getNodeName()))
       for (Node template = list.getFirstChild();
           template != null;
           template = template.getNextSibling())
         if ("template".equals(template.getNodeName())) parseTemplate(template);
 }
コード例 #28
0
 private String extractUser(Document document) throws SAXException {
   NodeList nodes = document.getFirstChild().getChildNodes();
   for (int i = 0; i < nodes.getLength(); i++) {
     if ("audit".equals(nodes.item(i).getNodeName())) {
       return XMLUtils.getNode(nodes.item(i), "user").getFirstChild().getNodeValue();
     }
   }
   throw new SAXException("Balise audit introuvable !");
 }
コード例 #29
0
 public void testUpdateSequenceEqualsGet() throws Exception {
   Document dom =
       getAsDOM(BASEPATH + "?request=GetCapabilities&service=WCS&version=1.0.0&updateSequence=0");
   // print(dom);
   final Node root = dom.getFirstChild();
   assertEquals("ServiceExceptionReport", root.getNodeName());
   assertEquals(
       "CurrentUpdateSequence",
       root.getFirstChild().getNextSibling().getAttributes().getNamedItem("code").getNodeValue());
 }
コード例 #30
0
ファイル: FileHandler.java プロジェクト: 6/CS-Projects
  /**
   * Loads a given XML string and returns a list of its SoundResources.
   *
   * @param xmlString of XML to parse.
   * @return list of SoundResources
   * @throws IOException when an I/O error occurs
   * @throws SAXException when an XML parsing error is encountered
   */
  public List<SoundResource> loadFromString(String xmlString) throws SAXException, IOException {

    // Convert the string to a Document
    StringReader reader = new StringReader(xmlString);
    InputSource inputSource = new InputSource(reader);
    Document document = docBuilder.parse(inputSource);

    // get all child sounds, start at the root node from the Document
    return getSoundResources(document.getFirstChild().getChildNodes());
  }