コード例 #1
1
  private final void roundTrip(boolean expand, boolean validating, String encoding, String expect) {
    String docloc =
        this.getClass().getPackage().getName().replaceAll("\\.", "/") + "/TestIssue008.xml";
    URL docurl = ClassLoader.getSystemResource(docloc);

    if (docurl == null) {
      throw new IllegalStateException("Unable to get resource " + docloc);
    }

    SAXBuilder builder = new SAXBuilder(validating);
    // builder.setValidation(validating);
    builder.setExpandEntities(expand);
    Document doc = null;
    try {
      doc = builder.build(docurl);
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (doc == null) {
      fail("Unable to parse document, see output.");
    }

    Format fmt = Format.getCompactFormat();
    if (encoding != null) {
      fmt.setEncoding(encoding);
    }
    XMLOutputter xout = new XMLOutputter(fmt);

    String actual = xout.outputString(doc.getRootElement());
    assertEquals(expect, actual);
  }
コード例 #2
0
ファイル: NcmlParserUtil.java プロジェクト: feihugis/NetCDF
  public static List getNcMLElements(String path, Document doc) {

    // XPath doesn't support default namespaces, so we add nc as a prefix for the tags within the
    // namespace!!!
    if (!path.startsWith(NS_PREFIX_ON_TAG) && !path.startsWith("/")) path = NS_PREFIX_ON_TAG + path;

    Pattern pattern = Pattern.compile("/\\w");
    Matcher matcher = pattern.matcher(path);

    StringBuilder sb = new StringBuilder();
    int currentChar = 0;
    while (matcher.find()) {

      sb.append(path.substring(currentChar, matcher.start() - currentChar + 1));
      if (!sb.toString().endsWith("/")) sb.append("/");
      sb.append(NS_PREFIX_ON_TAG);
      currentChar = matcher.start() + 1;
    }

    sb.append(path.substring(currentChar, path.length()));

    XPath xpath;
    try {

      xpath = XPath.newInstance(sb.toString());
      xpath.addNamespace(NS_PREFIX, doc.getRootElement().getNamespaceURI());
      return xpath.selectNodes(doc);

    } catch (JDOMException e) {

      e.printStackTrace();
    }

    return null;
  }
コード例 #3
0
  @Override
  public void loadConfig(File f) {
    File configFile = new File(f, this.getName());
    if (!configFile.exists()) return;
    List<String> childStrings = null;
    try {
      childStrings = this.getXmlChildStrings(configFile);
    } catch (JDOMException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    } catch (IOException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    }

    JAXBContext jaxbContext = null;
    try {
      jaxbContext = JAXBContext.newInstance(Node.class);

      for (String xml : childStrings) {
        final Node node = (Node) jaxbContext.createUnmarshaller().unmarshal(new StringReader(xml));
        this.addManagedObject(node);
      }

    } catch (JAXBException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #4
0
ファイル: QueryThread.java プロジェクト: brunasousa/jpameter
  private String chooserQuery() {
    Random r = new Random();
    File experimentFile = new File(queryFile);
    SAXBuilder sb = new SAXBuilder();
    Document d = null;
    try {
      d = sb.build(experimentFile);
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    List<String> queries = new ArrayList<String>();

    Element jpameterTag = d.getRootElement();
    Element queriesTag = jpameterTag.getChild("queries");

    List<Element> query = queriesTag.getChildren();

    for (Element e : query) {
      Element type = e.getChild("type");
      if (Integer.parseInt(type.getValue()) == typeQuery + 1) {
        Element sql = e.getChild("sql");
        queries.add(sql.getValue());
      }
    }
    if (queries.size() > 0) return queries.get(r.nextInt(queries.size()));
    else return null;
  }
コード例 #5
0
ファイル: Pref.java プロジェクト: keensta/RwEditor
  private void setData() {
    try {
      Document doc = builder.build(prefFile);

      Element rootNode = doc.getRootElement();
      Element RWDir = new Element("RWDir");

      rootNode.getChild("firstLoad").setText("no");
      RWDir.setText(RWDIRECTORY.getAbsolutePath());

      rootNode.addContent(RWDir);

      XMLOutputter xmlOutput = new XMLOutputter();
      FileWriter fw = new FileWriter(prefFile);

      xmlOutput.setFormat(Format.getPrettyFormat());
      xmlOutput.output(doc, fw);

      fw.close();
    } catch (IOException io) {
      io.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
ファイル: AutoRefMap.java プロジェクト: arahpthos/AutoReferee
  /**
   * Get map info object associated with a zip
   *
   * @param zip zip file containing a configuration file
   * @return map info object if zip contains a map, otherwise null
   */
  public static AutoRefMap getMapInfo(File zip) {
    // skip non-directories
    if (zip.isDirectory()) return null;

    Element worldConfig;
    try {
      worldConfig = getConfigFileData(zip);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } catch (JDOMException e) {
      e.printStackTrace();
      return null;
    }

    String mapName = "??", version = "1.0";
    Element meta = worldConfig.getChild("meta");
    if (meta != null) {
      mapName = AutoRefMatch.normalizeMapName(meta.getChildText("name"));
      version = meta.getChildText("version");
    }

    try {
      return new AutoRefMap(mapName, version, zip);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #7
0
 public LocaleExtractor(
     MavenProjectInfo mavenProjectInfo, String manifestFileName, String phrescoTargetDir)
     throws Exception {
   try {
     System.setProperty(
         "javax.xml.parsers.SAXParserFactory",
         "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
     builder = new SAXBuilder();
     // disabling xml validation
     builder.setValidation(false);
     builder.setIgnoringElementContentWhitespace(true);
     loc = mavenProjectInfo.getBaseDir() + File.separator + phrescoTargetDir;
     loopDoc =
         builder.build(
             new File(
                 mavenProjectInfo.getBaseDir()
                     + mavenProjectInfo
                         .getProject()
                         .getProperties()
                         .getProperty("phresco.theme.target.dir")
                     + File.separator
                     + mavenProjectInfo
                         .getProject()
                         .getProperties()
                         .getProperty("phresco.theme.config.name")));
   } catch (JDOMException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #8
0
ファイル: AutoRefMap.java プロジェクト: arahpthos/AutoReferee
  /**
   * Gets maps that are not installed, but may be downloaded.
   *
   * @return set of all maps available for download
   */
  public static Set<AutoRefMap> getRemoteMaps() {
    // check the cache first, we might want to just use the cached value
    long time = ManagementFactory.getRuntimeMXBean().getUptime() - _cachedRemoteMapsTime;
    if (_cachedRemoteMaps != null && time < AutoRefMap.REMOTE_MAP_CACHE_LENGTH)
      return _cachedRemoteMaps;

    Set<AutoRefMap> maps = Sets.newHashSet();
    String repo = AutoRefMatch.getMapRepo();

    try {
      Map<String, String> params = Maps.newHashMap();
      params.put("prefix", "maps/");

      for (; ; ) {
        String url = String.format("%s?%s", repo, QueryUtil.prepareParams(params));
        Element listing = new SAXBuilder().build(new URL(url)).getRootElement();
        assert "ListBucketResult".equals(listing.getName()) : "Unexpected response";
        Namespace ns = listing.getNamespace();

        String lastkey = null;
        for (Element entry : listing.getChildren("Contents", ns)) {
          lastkey = entry.getChildTextTrim("Key", ns);
          if (!lastkey.endsWith(".zip")) continue;

          String[] keyparts = lastkey.split("/");
          String mapfile = keyparts[keyparts.length - 1];

          String mapslug = mapfile.substring(0, mapfile.length() - 4);
          String slugparts[] = mapslug.split("-v");

          if (slugparts.length < 2) {
            AutoReferee.log("Invalid map filename: " + mapfile, Level.WARNING);
            AutoReferee.log("Map files should be of the form \"MapName-vX.X.zip\"", Level.WARNING);
          } else {
            String etag = entry.getChildTextTrim("ETag", ns);
            maps.add(
                new AutoRefMap(
                    slugparts[0], slugparts[1], lastkey, etag.substring(1, etag.length() - 1)));
          }
        }

        // stop looping if the result says that it hasn't been truncated (no more results)
        if (!Boolean.parseBoolean(listing.getChildText("IsTruncated", ns))) break;

        // use the last key as a marker for the next pass
        if (lastkey != null) params.put("marker", lastkey);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }

    _cachedRemoteMapsTime = ManagementFactory.getRuntimeMXBean().getUptime();
    return _cachedRemoteMaps = maps;
  }
コード例 #9
0
  public void replaceParameter(MavenProjectInfo mavenProjectInfo, String phrescoTargetDir)
      throws Exception {
    try {
      Map getEnv = getEnvironmentDetails(mavenProjectInfo, phrescoTargetDir);
      System.out.println(getEnv);
      String installFile =
          mavenProjectInfo.getBaseDir()
              + File.separator
              + mavenProjectInfo
                  .getProject()
                  .getProperties()
                  .getProperty("phresco.install.site.file.path")
              + File.separator
              + mavenProjectInfo
                  .getProject()
                  .getProperties()
                  .getProperty("phresco.install.site.file.name");
      try {
        String line = "", content = "";
        String currentLine;
        BufferedReader reader = null;

        // Read the file content as string
        reader = new BufferedReader(new FileReader(installFile));
        while ((currentLine = reader.readLine()) != null) {
          content += currentLine + "\n";
        }
        reader.close();

        // Replace strings
        String newtext = content.replaceAll("SITE_FOLDER", (String) getEnv.get("context"));
        newtext = newtext.replaceAll("PATH_TO_SITE", (String) getEnv.get("deploy_dir"));
        newtext = newtext.replaceAll("DB_USER", (String) getEnv.get("username"));
        newtext = newtext.replaceAll("DB_PASS", (String) getEnv.get("password"));
        newtext = newtext.replaceAll("DB_HOST", (String) getEnv.get("host"));
        newtext = newtext.replaceAll("DB_DATABASE", (String) getEnv.get("dbname"));

        // Write the update string to the same file
        FileWriter writer = new FileWriter(installFile);
        writer.write(newtext);
        writer.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #10
0
ファイル: Classifier.java プロジェクト: jhary82/ISys
  /**
   * Konstruktor - Klassifizierungs-XML mit dem "Brain"
   *
   * @param xml - Name der XML-Datei
   */
  public Classifier(File xml) {
    try {
      Document doc = new SAXBuilder().build(xml);
      Element root = doc.getRootElement();
      List<Element> children = root.getChildren();
      film = new Classifier_Class(children.get(0));
      news = new Classifier_Class(children.get(1));

    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #11
0
ファイル: XmlUtil.java プロジェクト: xiangbai/DCOPSolver
 public static Document openXmlDocument(String path) {
   SAXBuilder builder = new SAXBuilder();
   try {
     Document doc = builder.build(new File(path));
     return doc;
   } catch (JDOMException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
コード例 #12
0
ファイル: Ejercicio14.java プロジェクト: alvarogomezmu/dam
  public static void main(String[] args) {
    Document doc = null;

    try {
      doc = new SAXBuilder().build("C:\\petra\\universidad.xml");
    } catch (JDOMException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Nombre de la carrera que estudia Víctor Manuel
    Herramientas.xpath(
        doc, "//carrera[@id=//alumno[nombre='Víctor Manuel']//carrera/@codigo]/nombre");
  }
コード例 #13
0
ファイル: AnimationSet.java プロジェクト: Sunnyharry/gruppe21
  public AnimationSet(String sn, String type) {
    setName = sn;
    try {
      setXML = new SAXBuilder().build(GameConstants.ANIMATION_FILES_DIR + type + "/" + sn + ".xml");
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    setRoot = setXML.getRootElement();
    // reads animation  xml file , loads animations in animationlist
    // TODO optimieren , ist das mit den einzelbildern sinnvoll ?
    List<Element> animations = setRoot.getChildren("animation");
    List<Element> stills = setRoot.getChildren("still");

    defaultImage =
        new GameImage(
            GameConstants.ANIMATION_FILES_DIR + type + "/" + setRoot.getAttributeValue("default"),
            "default");

    defaultAnimation =
        new GameAnimation(
            "default",
            1,
            GameConstants.ANIMATION_FILES_DIR + type + "/" + setRoot.getAttributeValue("default"),
            1);

    for (int i = 0; i < animations.size(); i++) {
      animationList.add(
          new GameAnimation(
              animations.get(i).getAttributeValue("name"),
              Integer.parseInt(animations.get(i).getAttributeValue("frames")),
              GameConstants.ANIMATION_FILES_DIR + type + "/" + animations.get(i).getText(),
              Integer.parseInt(animations.get(i).getAttributeValue("stretch"))));
    }

    for (int i = 0; i < stills.size(); i++) {
      imageList.add(
          new GameImage(
              GameConstants.ANIMATION_FILES_DIR + type + "/" + stills.get(i).getText(),
              GameConstants.ANIMATION_FILES_DIR
                  + type
                  + "/"
                  + stills.get(i).getAttributeValue("name")));
    }
  }
コード例 #14
0
ファイル: Pref.java プロジェクト: ubrot/RwEditor
  public void loadData() {
    try {
      Document doc = builder.build(prefFile);
      Element rootNode = doc.getRootElement();

      if (rootNode.getChildText("firstLoad").equals("yes")) {
        return;
      }

      MODDIRECTORY = new File(rootNode.getChildText("ModDir"));

    } catch (IOException io) {
      io.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
コード例 #15
0
  public static void main(String[] args) {

    long start = System.currentTimeMillis();

    try {
      // 获取JDOM解析器
      SAXBuilder builder = new SAXBuilder();
      // 解析文件
      File file = new File("xml/books.xml");
      Document document = builder.build(file);

      // 写入XML文件
      FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/aaa.xml"));
      XMLOutputter xmlOutputter = new XMLOutputter();
      xmlOutputter.output(document, fileOutputStream);
      fileOutputStream.close();

      // 获取根节点
      Element root = document.getRootElement();
      // 获取子节点列表
      List<Element> books = root.getChildren();
      // 循环遍历子节点
      for (int i = 0; i < books.size(); i++) {
        // 获取某一个子节点
        Element book = books.get(i);
        // 获取得属性值
        String isbn = book.getAttributeValue("isbn");
        System.out.print("isbn: " + isbn);
        List<Element> childrenList = book.getChildren();
        for (Element element : childrenList) {
          System.out.print("   " + element.getName() + ": ");
          System.out.print(element.getText());
        }
        System.out.println("");
      }
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    long end = System.currentTimeMillis();
    System.out.println("耗时: " + (end - start));
  }
コード例 #16
0
ファイル: Pref.java プロジェクト: keensta/RwEditor
  public void loadData() {
    try {
      Document doc = builder.build(prefFile);
      Element rootNode = doc.getRootElement();

      if (rootNode.getChildText("firstLoad").equals("yes")) {
        return;
      }

      setRWDirectory(new File(rootNode.getChildText("RWDir")));
      setModDirectory(new File(RWDIRECTORY + "//Mods//"));
      firstLoad = "no";

    } catch (IOException io) {
      io.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
コード例 #17
0
  /**
   * retrieve all radar stations in this dataset collection
   *
   * @param stsXML_location _more_
   * @return station hashmap
   * @throws IOException _more_
   */
  public HashMap<String, Station> readRadarStations(String stsXML_location) throws IOException {
    SAXBuilder builder;
    Document doc = null;
    XMLEntityResolver jaxp = new XMLEntityResolver(true);
    builder = jaxp.getSAXBuilder();
    HashMap<String, Station> stations = new HashMap<String, Station>();

    try {
      doc = builder.build(stsXML_location);
    } catch (JDOMException e) {
      e.printStackTrace();
    }

    Element rootElem = doc.getRootElement();
    List<Element> children = rootElem.getChildren();
    for (Element child : children) {
      Station s;
      if (null != (s = readStation(child))) {
        stations.put(s.getName(), s);
      }
    }

    return stations;
  }
コード例 #18
0
  public static void removeEventinXmlFilter() {
    Filter filtre =
        new Filter() {
          // On défini les propriétés du filtre à l'aide
          // de la méthode matches
          public boolean matches(Object ob) {
            //		         //1 ère vérification : on vérifie que les objets
            //		         //qui seront filtrés sont bien des Elements
            //		         if(!(ob instanceof Element)){return false;}
            //
            //		         //On crée alors un Element sur lequel on va faire les
            //		         //vérifications suivantes.
            //		         Element element = (Element)ob;
            //
            //		         //On crée deux variables qui vont nous permettre de vérifier
            //		         //les conditions de nom et de prenom
            //		         int verifNom = 0;
            //		         int verifPrenom = 0;
            //
            //		         //2 ème vérification: on vérifie que le nom est bien "CynO"
            //		         if(element.getAttribute("nomEvent").getValue().equalsIgnoreCase("event1"))
            ////		         if(element.getChild("nom").getTextTrim().equals("CynO"))
            //		         {
            //		            verifNom = 1;
            //		         }
            //		         //Si nos conditions sont remplies on retourne true, false sinon
            //		         if(verifNom == 1)
            //		         {
            //		            return true;
            //		         }
            //		         return false;
            return true;
          }

          @Override
          public Filter and(Filter arg0) {
            // TODO Auto-generated method stub
            return null;
          }

          @Override
          public List filter(List arg0) {
            // TODO Auto-generated method stub
            return null;
          }

          @Override
          public Object filter(Object arg0) {
            // TODO Auto-generated method stub
            return null;
          }

          @Override
          public Filter negate() {
            // TODO Auto-generated method stub
            return null;
          }

          @Override
          public Filter or(Filter arg0) {
            // TODO Auto-generated method stub
            return null;
          }

          @Override
          public Filter refine(Filter arg0) {
            // TODO Auto-generated method stub
            return null;
          }
        }; // Fin du filtre

    // getContent va utiliser notre filtre pour créer une liste d'étudiants répondant
    // à nos critères.
    SAXBuilder sxbuilder = new SAXBuilder();
    Document document;
    try {
      document = sxbuilder.build(new File(xmlDefaultPath));
      Element racine = document.getRootElement();
      List resultat = racine.getContent(filtre);
      System.out.println("size" + resultat.size() + "##");
      // On affiche enfin l'attribut classe de tous les éléments de notre list
      Iterator i = resultat.iterator();
      while (i.hasNext()) {
        Element courant = (Element) i.next();
        System.out.println(courant.getAttributeValue("nomEvent"));
      }

    } catch (JDOMException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #19
0
ファイル: AutoRefMap.java プロジェクト: arahpthos/AutoReferee
    @Override
    public void run() {
      // get remote map directory
      Map<String, AutoRefMap> remote = Maps.newHashMap();
      for (AutoRefMap map : getRemoteMaps()) remote.put(map.name, map);

      for (File folder : AutoRefMap.getMapLibrary().listFiles())
        if (folder.isDirectory())
          try {
            File arxml = new File(folder, AutoReferee.CFG_FILENAME);
            if (!arxml.exists()) continue;

            Element arcfg = new SAXBuilder().build(arxml).getRootElement();
            Element meta = arcfg.getChild("meta");
            if (meta != null) {
              AutoRefMap rmap =
                  remote.get(AutoRefMatch.normalizeMapName(meta.getChildText("name")));
              if (rmap != null && rmap.getZip() != null) {
                FileUtils.deleteQuietly(folder);
                AutoReferee.getInstance()
                    .sendMessageSync(
                        sender,
                        String.format(
                            "Updated %s to new format (%s)", rmap.name, rmap.getVersionString()));
              }
            }
          } catch (IOException e) {
            e.printStackTrace();
          } catch (JDOMException e) {
            e.printStackTrace();
          }

      // check for updates on installed maps
      for (AutoRefMap map : getInstalledMaps())
        try {
          // get the remote version and check if there is an update
          AutoRefMap rmap;
          if ((rmap = remote.get(map.name)) != null) {
            boolean needsUpdate = map.md5sum != null && !map.md5sum.equals(rmap.md5sum);
            if (force || needsUpdate) {
              AutoReferee.getInstance()
                  .sendMessageSync(
                      sender,
                      String.format(
                          "UPDATING %s (%s -> %s)...", rmap.name, map.version, rmap.version));
              if (rmap.getZip() == null)
                AutoReferee.getInstance()
                    .sendMessageSync(sender, "Update " + ChatColor.RED + "FAILED");
              else {
                AutoReferee.getInstance()
                    .sendMessageSync(
                        sender,
                        "Update "
                            + ChatColor.GREEN
                            + "SUCCESS: "
                            + ChatColor.RESET
                            + rmap.getVersionString());
                FileUtils.deleteQuietly(map.getZip());
              }
            }
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
    }