Пример #1
0
  /**
   * Parse a file, which should have a root which is the associated tag.
   *
   * @param in File to parse
   * @param tag Root tag which the parsed file should contain
   */
  public static void parse(File in, XmlTagHandler tag) throws XmlParseException {
    SAXBuilder builder;
    Document doc;

    builder = new SAXBuilder();
    InputStream is = null;

    // open the file ourselves.  the builder(File)
    // method escapes " " -> "%20" and bombs
    try {
      is = new FileInputStream(in);
      doc = builder.build(is);
    } catch (IOException exc) {
      throw new XmlParseException(exc.getMessage());
    } catch (JDOMException exc) {
      throw new XmlParseException(exc.getMessage());
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
        }
      }
    }
    generalParse(tag, doc);
  }
Пример #2
0
  @SuppressWarnings("unchecked")
  private List<JarConfig> loadConfig() {
    List<JarConfig> list_pair = new ArrayList<JarConfig>();
    SAXBuilder builder = new SAXBuilder();

    try {
      Document document = builder.build(this.config);
      Element root = document.getRootElement();
      Element ele = (Element) XPath.selectSingleNode(root, path.JAR.toString());
      List<Element> list = ele.getChildren();
      for (Element element : list) {
        JarConfig config =
            new JarConfig(
                classPath + element.getAttributeValue("jar").trim(),
                element.getAttributeValue("name").trim(),
                element.getAttributeValue("class").trim());

        list_pair.add(config);
      }
    } catch (JDOMException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());

    } catch (IOException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      WriteToLog.error("XML ERROR!" + "\n" + e.getMessage());
    }
    return list_pair;
  }
  private void parseConfigFile(File configFile) throws IOException, JDOMException {
    /* check for valid xml */
    if (XMLValidityChecker.validateXML(configFile.getAbsolutePath())) {

      SAXBuilder saxBuilder = new SAXBuilder();
      Document document = saxBuilder.build(configFile);
      Element rootElement = document.getRootElement();

      hasGoldGroup = false;

      Iterator childrenIterator = rootElement.getChildren().iterator();

      while (childrenIterator.hasNext()) {
        Element childElement = (Element) childrenIterator.next();
        if (childElement.getName().equals(ANNOTATION_GROUP_TAG)) {
          processAnnotationGroupElement(childElement);
        } else if (childElement.getName().equals(COMPARISON_GROUP_TAG)) {
          processComparisonGroupElement(childElement);
        } else {
          logger.warn(
              "Unexpected element encountered while parsing the comparison configuration file: "
                  + childElement.getName());
        }
      }

    } else {
      logger.error(
          "Comparison configuration file is not well-formed XML. Please fix and try again.");
    }
  }
Пример #4
0
  private void readFile(String fileName) throws JDOMException, IOException {
    String absolutePath = getAbsolutePath(fileName);
    File xmlFile = new File(absolutePath);

    SAXBuilder builder = new SAXBuilder();
    this.doc = builder.build(xmlFile);
  }
Пример #5
0
  public String SqlExcute(String xmlStr) {
    String outstr = "false";
    Document doc;
    Element rootNode;
    String intStr = Basic.decode(xmlStr);

    try {
      Reader reader = new StringReader(intStr);
      SAXBuilder ss = new SAXBuilder();
      doc = ss.build(reader);

      rootNode = doc.getRootElement();

      List list = rootNode.getChildren();

      DBTable datatable = new DBTable();

      for (int i = 0; i < list.size(); i++) {
        Element childRoot = (Element) list.get(i);
        // System.out.print(childRoot.getText());
        outstr = String.valueOf(datatable.SaveDateStr(childRoot.getText()));
      }

    } catch (JDOMException ex) {
      System.out.print(ex.getMessage());
    }
    return outstr;
  }
Пример #6
0
  public UserEntrySet(InputStream stream, String urlPrefix)
      throws JDOMException, IOException, UnexpectedRootElementException {
    SAXBuilder sb = new SAXBuilder();
    Document d = sb.build(stream);

    populate(d, urlPrefix);
  }
Пример #7
0
  /**
   * Processes the messages from the server
   *
   * @param message
   */
  private synchronized void processServerMessage(String message) {
    SAXBuilder builder = new SAXBuilder();
    String what = new String();
    Document doc = null;

    try {
      doc = builder.build(new StringReader(message));
      Element root = doc.getRootElement();
      List childs = root.getChildren();
      Iterator i = childs.iterator();
      what = ((Element) i.next()).getName();
    } catch (Exception e) {
    }

    if (what.equalsIgnoreCase("LOGIN") == true) _login(doc);
    else if (what.equalsIgnoreCase("LOGOUT") == true) _logout(doc);
    else if (what.equalsIgnoreCase("MESSAGE") == true) _message(doc);
    else if (what.equalsIgnoreCase("WALL") == true) _wall(doc);
    else if (what.equalsIgnoreCase("CREATEGROUP") == true) _creategroup(doc);
    else if (what.equalsIgnoreCase("JOINGROUP") == true) _joingroup(doc);
    else if (what.equalsIgnoreCase("PARTGROUP") == true) _partgroup(doc);
    else if (what.equalsIgnoreCase("GROUPMESSAGE") == true) _groupmessage(doc);
    else if (what.equalsIgnoreCase("KICK") == true) _kick(doc);
    else if (what.equalsIgnoreCase("LISTUSER") == true) _listuser(doc);
    else if (what.equalsIgnoreCase("LISTGROUP") == true) _listgroup(doc);
  }
Пример #8
0
  private void loadData(File path) {
    if (path.isDirectory()) {
      File[] dataFiles = path.listFiles(new XMLFilter());
      SAXBuilder builder = new SAXBuilder();
      GeneratorDtdResolver resolver = new GeneratorDtdResolver(path);
      builder.setEntityResolver(resolver);

      for (int i = 0; i < dataFiles.length; i++) {
        try {
          URL url = dataFiles[i].toURI().toURL();
          Document nameSet = builder.build(url);
          DocType dt = nameSet.getDocType();

          if (dt.getElementName().equals("GENERATOR")) {
            loadFromDocument(nameSet);
          }

          nameSet = null;
          dt = null;
        } catch (Exception e) {
          Logging.errorPrint(e.getMessage(), e);
          JOptionPane.showMessageDialog(this, "XML Error with file " + dataFiles[i].getName());
        }
      }

      loadDropdowns();
    } else {
      JOptionPane.showMessageDialog(this, "No data files in directory " + path.getPath());
    }
  }
  public void cargarConfiguracion() throws ConfiguracionException {

    try {
      SAXBuilder builder = new SAXBuilder();
      File xmlFile = new File(this.getPathConfig());
      Document document = (Document) builder.build(xmlFile);
      Element rootNode = document.getRootElement();
      this.setHoraUnificador(Integer.valueOf(rootNode.getChildText("horaUnificador")));
      this.setMinutoUnificador(Integer.valueOf(rootNode.getChildText("minutoUnificador")));
      this.setManianaOTardeUnificador(rootNode.getChildText("manianaOTardeUnificador"));

      this.setSmtp(rootNode.getChildText("smtp"));
      this.setPuerto(rootNode.getChildText("puerto"));
      this.setDesdeMail(rootNode.getChildText("desde"));
      this.setTLS(Boolean.valueOf(rootNode.getChildText("tls")));
      this.setAuth(Boolean.valueOf(rootNode.getChildText("auth")));
      this.setUser(rootNode.getChildText("user"));
      this.setPassword(rootNode.getChildText("password"));

      this.setIpBD(rootNode.getChildText("ipBD"));
      this.setPortBD(rootNode.getChildText("portBD"));

      this.setPathTempImages(rootNode.getChildText("pathTempImages"));
      this.setPathExportDesign(rootNode.getChildText("pathExportDesign"));
      this.setPathConfig(rootNode.getChildText("pathConfig"));
      this.setPathDownloadApp(rootNode.getChildText("pathDownloadApp"));
      this.setKeyGoogleMap(rootNode.getChildText("keyGoogleMap"));

    } catch (Exception e) {
      LogFwk.getInstance(Configuracion.class)
          .error("Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
      throw new ConfiguracionException(
          "Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
    }
  }
Пример #10
0
  public static void main(String[] args) {

    if (args.length == 0) {
      System.out.println("Usage: java JDOMValidator URL");
      return;
    }

    SAXBuilder builder = new SAXBuilder(true);
    //  ^^^^
    // Turn on validation

    // command line should offer URIs or file names
    try {
      builder.build(args[0]);
      // If there are no well-formedness or validity errors,
      // then no exception is thrown.
      System.out.println(args[0] + " is valid.");
    }
    // indicates a well-formedness or validity error
    catch (JDOMException e) {
      System.out.println(args[0] + " is not valid.");
      System.out.println(e.getMessage());
    } catch (IOException e) {
      System.out.println("Could not check " + args[0]);
      System.out.println(" because " + e.getMessage());
    }
  }
Пример #11
0
 @Override
 public void processExistingResource(
     HttpManager manager, Request request, Response response, Resource resource)
     throws NotAuthorizedException, BadRequestException, ConflictException {
   try {
     org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder();
     // Prevent possibily of malicious clients using remote the parser to load remote resources
     builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
     org.jdom.Document doc = builder.build(request.getInputStream());
     String reportName = doc.getRootElement().getName();
     Report r = reports.get(reportName);
     if (r == null) {
       log.error("report not known: " + reportName);
       throw new BadRequestException(resource);
     } else {
       log.info("process report: " + reportName + " with : " + r.getClass());
       String xml = r.process(request.getHostHeader(), request.getAbsolutePath(), resource, doc);
       if (log.isTraceEnabled()) {
         log.trace("Report XML:\n" + xml);
       }
       response.setStatus(Response.Status.SC_MULTI_STATUS);
       response.setContentTypeHeader("text/xml");
       response.setEntity(new ByteArrayEntity(xml.getBytes("UTF-8")));
     }
   } catch (JDOMException ex) {
     java.util.logging.Logger.getLogger(ReportHandler.class.getName()).log(Level.SEVERE, null, ex);
   } catch (ReadingException ex) {
     throw new RuntimeException(ex);
   } catch (WritingException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
Пример #12
0
  @Parameters
  public static Collection<FitsOutput[]> data() throws Exception {
    Fits fits = new Fits("");
    SAXBuilder builder = new SAXBuilder();
    //		List<FitsOutput[]> inputs = new ArrayList<String[][]>();
    List<FitsOutput[]> inputs = new ArrayList<FitsOutput[]>();

    File inputDir = new File("tests/input");
    File outputDir = new File("tests/output");

    for (File input : inputDir.listFiles()) {
      // skip directories
      if (input.isDirectory()) {
        continue;
      }
      FitsOutput fitsOut = fits.examine(input);

      File outputFile = new File(outputDir + File.separator + input.getName() + ".xml");
      if (!outputFile.exists()) {
        System.err.println("Not Found: " + outputFile.getPath());
        continue;
      }
      Document expectedXml = builder.build(new FileInputStream(outputFile));
      FitsOutput expectedFits = new FitsOutput(expectedXml);

      FitsOutput[][] tmp = new FitsOutput[][] {{expectedFits, fitsOut}};
      inputs.add(tmp[0]);
    }
    return inputs;
  }
  /**
   * @param args
   * @throws IOException
   * @throws FileNotFoundException
   * @throws JDOMException
   */
  public static void main(String[] args) throws FileNotFoundException, IOException, JDOMException {
    String xmlpath = "c:/catalog.xml";
    // 使用JDOM首先要指定使用什么解析器
    SAXBuilder builder = new SAXBuilder(false); // 这表示使用的是默认的解析器
    // 得到Document,以后要进行的所有操作都是对这个Document操作的
    Document doc = builder.build(xmlpath);
    // 得到根元素
    Element root = doc.getRootElement();
    // 得到元素(节点)的集合
    List bookslist = root.getChildren("books");
    // 轮循List集合
    for (Iterator iter = bookslist.iterator(); iter.hasNext(); ) {
      Element books = (Element) iter.next();
      List bookList = books.getChildren("book");
      for (Iterator it = bookList.iterator(); it.hasNext(); ) {
        Element book = (Element) it.next();
        // 取得元素的属性
        String level = book.getAttributeValue("level");
        System.out.println(level);
        // 取得元素的子元素(为最低层元素)的值 注意的是,必须确定book元素的名为“name”的子元素只有一个。
        String author = book.getChildTextTrim("author");
        System.out.println(author);
        // 改变元素(为最低层元素)的值;对Document的修改,并没有在实际的XML文档中进行修改
        book.getChild("author").setText("author_test");
      }
    }
    // 保存Document的修改到XML文件中
    // XMLOutputter outputter=new XMLOutputter();
    // outputter.output(doc,new FileOutputStream(xmlpath));

  }
  /**
   * Create a jDOM document from an xml string
   *
   * @param string
   * @return
   */
  public static Document getDocumentFromString(String string, String encoding) {

    if (encoding == null) {
      encoding = CommonUtils.encoding;
    }

    byte[] byteArray = null;
    try {
      byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e1) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);

    // Reader reader = new StringReader(hOCRText);
    SAXBuilder builder = new SAXBuilder(false);
    Document document = null;

    try {
      document = builder.build(baos);
    } catch (JDOMException e) {
      System.err.println("error " + e.toString());
      return null;
    } catch (IOException e) {
      System.err.println(e.toString());
      return null;
    }
    return document;
  }
Пример #15
0
 /**
  * Initialize all the exporters
  *
  * @param file the {@link File} with the exporters to intialize
  * @throws ExportException when cannot read from the file
  */
 public static void initializeExporters(File file) throws ExportException {
   BufferedReader reader = null;
   try {
     reader = new BufferedReader(new FileReader(file));
     // if(reader==null)
     // {
     // String params[]={file.getAbsolutePath()};
     // throw new
     // ExportException(StringUtilities.getReplacedString(PropertiesHandler.getResourceString("error.algorithm.file"),params));
     // }
     SAXBuilder builder = new SAXBuilder(true);
     builder.setEntityResolver(new NetworkEntityResolver());
     Document doc = builder.build(reader);
     loadFromDocument(doc);
   } catch (FileNotFoundException e) {
     throw new ExportException(e.getMessage());
   } catch (JDOMException e) {
     throw new ExportException(e.getMessage());
   } catch (Exception e) {
     throw new ExportException(e.getMessage());
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException ignore) {
       }
     }
   }
 }
Пример #16
0
  static {
    SAXBuilder builder = new SAXBuilder();
    languageCode = prefs.get("uiLanguage", "deu");

    java.net.URL lfURL = new ResourceHandler().languageFileURL();

    try {
      Document doc = builder.build(lfURL);
      Element root = doc.getRootElement();
      List allElements = root.getChild("uiItems").getChildren();
      Iterator iterator = allElements.iterator();
      while (iterator.hasNext()) {
        Element myElement = (Element) iterator.next();
        if (myElement.getName() == "uiItem"
            && myElement.getAttributeValue("name") != null
            && myElement.getAttributeValue("value") != null
            && myElement.getAttributeValue("lang").equals(languageCode)) {
          UiElements.put(myElement.getAttributeValue("name"), myElement.getAttributeValue("value"));
        } else {
          //					System.err.println("uiElement in Languagefile invalid!");
        }
      }

    } catch (JDOMException e) {
      System.err.println("Languagefile invalid!");
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Languagefile missing!");
    }
  }
Пример #17
0
 public SAXBuilder builder() throws Exception {
   SAXBuilder builder = new SAXBuilder();
   if (this.removeProperties) {
     builder.setXMLFilter(new TagFilter("properties"));
   }
   return builder;
 }
Пример #18
0
  /**
   * Loads an xml file from a URL after posting content to the URL.
   *
   * @param url
   * @param xmlQuery
   * @return
   * @throws IOException
   * @throws JDOMException
   */
  public static Element loadFile(URL url, Element xmlQuery) throws IOException, JDOMException {
    Element result = null;
    try {
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "application/xml");
      connection.setRequestProperty(
          "Content-Length",
          "" + Integer.toString(getString(xmlQuery).getBytes(Jeeves.ENCODING).length));
      connection.setRequestProperty("Content-Language", "en-US");
      connection.setDoOutput(true);
      PrintStream out = new PrintStream(connection.getOutputStream(), true, Jeeves.ENCODING);
      out.print(getString(xmlQuery));
      out.close();

      SAXBuilder builder = getSAXBuilderWithoutXMLResolver(false); // new SAXBuilder();
      Document jdoc = builder.build(connection.getInputStream());

      result = (Element) jdoc.getRootElement().detach();
    } catch (Exception e) {
      Log.error(Log.ENGINE, "Error loading URL " + url.getPath() + " .Threw exception " + e);
      e.printStackTrace();
    }
    return result;
  }
Пример #19
0
  private SBOLRootObject createDnaComponent(String xml, SBOLDocument document) {
    SAXBuilder builder = new SAXBuilder();
    DnaComponent dnaComponent = SBOLFactory.createDnaComponent();
    try {
      Document doc = builder.build(new File(xml));
      Element rootEl = doc.getRootElement();

      Element list = rootEl.getChild("part_list").getChild("part");
      partId = Integer.parseInt(list.getChildText("part_id"));
      dnaComponent.setURI(URI.create(list.getChildText("part_url")));
      dnaComponent.setDisplayId(list.getChildText("part_name"));
      dnaComponent.setName(list.getChildText("part_short_name"));
      dnaComponent.setDescription(list.getChildText("part_short_desc"));
      Element seq = rootEl.getChild("part_list").getChild("part").getChild("sequences");

      dnaComponent.setDnaSequence(this.createDnaSequence(seq.getChildText("seq_data")));
      List<SequenceAnnotation> seqs = createAllDnaSubComponent(xml);
      System.out.println(seqs.size());
      for (int i = 0; i < seqs.size(); i++) dnaComponent.addAnnotation(seqs.get(i));

    } catch (JDOMException e) {
      //            e.printStackTrace();

    } catch (IOException e) {
      //            e.printStackTrace();
    }
    return dnaComponent;
  }
  /**
   * Shortcut for reading an Xml document
   *
   * @param path
   * @return the document, or null if the file doesn't exist yet
   * @throws org.jdom.JDOMException
   * @throws java.io.IOException
   */
  public static Document readDocument(String path) throws JDOMException, IOException {

    File f = new File(path);
    SAXBuilder sxb = new SAXBuilder();
    Document jDomDocument = sxb.build(f);
    return jDomDocument;
  }
Пример #21
0
 @SuppressWarnings("unchecked")
 @Override
 public String inportFlowbase(String flowBaseXml) {
   ByteArrayInputStream bais;
   try {
     bais = new ByteArrayInputStream(flowBaseXml.getBytes("UTF-8"));
     SAXBuilder saxBuilder = new SAXBuilder();
     Document doc = saxBuilder.build(bais);
     Element root = doc.getRootElement();
     Flowbase flowbase = XmlUtil.getBeanByElement(root, Flowbase.class);
     flowbase.setFlowName(flowbase.getFlowName() + "-副本");
     this.flowbaseDao.save(flowbase);
     List<Element> nodeList = root.getChildren("flownode");
     this.flownodeService.importFlowNode(flowbase.getId(), nodeList);
     // TODO 未完成
     return flowbase.getId();
   } catch (UnsupportedEncodingException e) {
     log.error(
         this.getClass().getSimpleName() + " e==> inportFlowbase,UnsupportedEncodingException", e);
     throw new BpmException("bpm003", "导入流程失败");
   } catch (JDOMException e) {
     log.error(this.getClass().getSimpleName() + " e==> inportFlowbase,JDOMException", e);
     throw new BpmException("bpm003", "导入流程失败");
   } catch (IOException e) {
     log.error(this.getClass().getSimpleName() + " e==> inportFlowbase,IOException", e);
     throw new BpmException("bpm003", "导入流程失败");
   }
 }
Пример #22
0
  void loadTemplates(InputStream inputStream, final String templateName) {
    final SAXBuilder parser = new SAXBuilder();
    try {

      TemplateSettings templateSettings = TemplateSettings.getInstance();
      Document doc = parser.build(inputStream);
      Element root = doc.getRootElement();
      for (Object element : root.getChildren()) {
        if (element instanceof Element) {
          final Template template = readExternal((Element) element, templateName);
          final String key = template.getKey();
          if (key != null) {
            TemplateImpl existingTemplate = templateSettings.getTemplate(key, TemplateGroupName);
            if (existingTemplate == null) {
              templateSettings.addTemplate(template);
            } else if (TemplateGroupName.equals(existingTemplate.getGroupName())) {
              // Update only add if template is in the AribaWeb group
              templateSettings.removeTemplate(existingTemplate);
              templateSettings.addTemplate(template);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #23
0
  public DataSource createDataSource() {

    SAXBuilder sb = new SAXBuilder();
    DataSource dataSource = null;
    try {
      Document xmlDoc = sb.build("config/data.xml");
      Element root = xmlDoc.getRootElement();
      Element url = root.getChild("url");

      dataSource = new DataSource();
      dataSource.setHost(url.getText());
      dataSource.setDbName(root.getChild("database").getText());
      dataSource.setDriverClass(root.getChildText("driver-class"));
      dataSource.setPort(root.getChildText("port"));
      dataSource.setUserLogin(root.getChildText("login"));
      dataSource.setUserPwd(root.getChildText("password"));

    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return dataSource;
  }
Пример #24
0
 public void createMessageFiles(String modelFileName) {
   try {
     System.out.println(modelFileName);
     msgs = new HashMap<String, MessageObject>();
     fields = new HashMap<String, List<FieldObject>>();
     String configFilePath = GeneratorHelper.getBuildPath(MODEL_DIC + modelFileName);
     SAXBuilder builder = new SAXBuilder();
     Document doc = builder.build(configFilePath);
     Element root = doc.getRootElement();
     String module = root.getAttributeValue("module"); // 所属模块
     List messages = root.getChildren("message", NAME_SPACE); // 消息体定义
     List constants = null;
     Element constantsElement = root.getChild("constants", NAME_SPACE);
     if (constantsElement != null) {
       constants = root.getChild("constants", NAME_SPACE).getChildren(); // 常量定义
     } else {
       constants = new ArrayList();
     }
     this.replaceMacros(messages);
     createServerFiles(messages, module);
     createClientFile(messages, module, constants);
     createServerMappingFile(messages, module);
     createRobotServerMappingFile(messages, module);
   } catch (Exception e) {
     logger.error("", e);
   }
 }
Пример #25
0
  public XMIVersionExtractor(File xmlFile) {
    try {
      SAXBuilder builder = new SAXBuilder();
      Document doc = builder.build(xmlFile);

      Element root = doc.getRootElement();
      if (root.getName().equals("XMI")) {
        String version = null;
        version = root.getAttributeValue("xmi.version");
        if (version != null) {
          this.version = version;
        } else {
          version = root.getAttributeValue("version", root.getNamespace());
          if (version != null) this.version = version;
        }
      } else {
        Element xmiRoot = root.getChild("XMI");
        if (xmiRoot != null) {
          String version = null;
          version = xmiRoot.getAttributeValue("xmi.version");
          if (version != null) {
            this.version = version;
          } else {
            version = xmiRoot.getAttributeValue("version", xmiRoot.getNamespace());
            if (version != null) this.version = version;
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
  private void loadTerminologyFromXML(String filename) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    InputStream input = this.getClass().getResourceAsStream(filename);
    try {
      Document doc = builder.build(input);
      Element root = doc.getRootElement();
      List codesets = root.getChildren("codeset");
      codeSetList.clear();
      groupList.clear();

      for (Iterator it = codesets.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        codeSetList.add(loadCodeSet(element));
      }

      List groups = root.getChildren("group");
      for (Iterator it = groups.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        groupList.add(loadGroup(element));
      }
    } finally {
      if (input != null) {
        input.close();
      }
    }
  }
Пример #27
0
  /**
   * Read the description of the Folder from the specified URL.
   *
   * @param url the URL of a web service providing the description of the Folder
   * @param treenode the JTree node that represents this Folder
   */
  private void readFolderFromURL(String url, DefaultMutableTreeNode treenode) {
    ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();

    // add the LoadDescription action
    list.add(new NameValuePair("Action", "LoadDescription")); // $NON-NLS-1$ //$NON-NLS-2$

    try {
      // get an input stream from the URL
      InputStream fin = getInputStream(url, list);

      // build the XML document
      SAXBuilder builder = new SAXBuilder();

      Document doc = builder.build(fin);

      // get the root Element in the document
      Element root = doc.getRootElement();

      readFolder(treenode, root);

    } catch (MalformedURLException ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.12") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.13") + url, ex); // $NON-NLS-1$
    } catch (JDOMException ex) {
      // indicates a well-formedness error
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.14") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.15") + url, ex); // $NON-NLS-1$
    } catch (IOException ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.16") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.17") + url, ex); // $NON-NLS-1$
    } catch (Exception ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.18") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.19") + url, ex); // $NON-NLS-1$
    }
  }
  /* (non-Javadoc)
   * @see org.hibernate.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object)
   */
  public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
      throws HibernateException, SQLException {
    byte[] bytes = rs.getBytes(names[0]);
    if (rs.wasNull()) {
      return null;
    }

    // TODO figure out how to inject this
    HomeFactory homeFactory = (HomeFactory) ComponentManager.getInstance().get("xmlHomeFactory");
    WritableObjectHome home = (WritableObjectHome) homeFactory.getHome("agent");

    StructuredArtifact artifact = (StructuredArtifact) home.createInstance();
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setFeature(
        "http://apache.org/xml/features/disallow-doctype-decl", true); // SAK-23245
    try {
      Document doc = saxBuilder.build(in);
      artifact.setBaseElement(doc.getRootElement());
    } catch (JDOMException e) {
      throw new HibernateException(e);
    } catch (IOException e) {
      throw new HibernateException(e);
    }
    return artifact;
  }
  /*
   * Liest die Scenario Informationen in die entsprechenden Objekte
   * und gibt eine Liste davon zurueck. Siehe dazu auch MeteringProcessStorage.java.
   * @param fileName Dateiname der Storagedatei
   * @return Liste mit den Scenario-Objekte.
   */
  public List getList() {
    List scenariosList = new ArrayList();
    try {
      SAXBuilder builder = new SAXBuilder();
      StorageDoc = builder.build(appPath + storageFileName);
      Root = StorageDoc.getRootElement();
      List scenarioChildren = Root.getChildren("scenario", ipfixConfigNS);
      Iterator listIterator = scenarioChildren.iterator();
      Element currentElement;

      while (listIterator.hasNext()) {
        currentElement = (Element) listIterator.next();
        Scenario currentScenario = new Scenario();
        // currentscenario.setId(Integer.valueOf(currentElement.getAttributeValue("id")));
        currentScenario.setName(currentElement.getChildText("name", ipfixConfigNS));
        currentScenario.setDescription(currentElement.getChildText("descript", ipfixConfigNS));
        List deviceList = new ArrayList();
        Element devices = currentElement.getChild("devices", ipfixConfigNS);
        List childList = devices.getChildren("device", ipfixConfigNS);
        Iterator devicesIterator = childList.iterator();
        while (devicesIterator.hasNext()) {
          Element currentDevice = (Element) devicesIterator.next();
          deviceList.add(currentDevice.getText());
        }
        currentScenario.setDeviceList(deviceList);
        scenariosList.add(currentScenario);
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return scenariosList;
  }
Пример #30
0
  public static void parse(InputStream is, XmlTagHandler tag, EntityResolver resolver)
      throws XmlParseException {
    SAXBuilder builder;
    Document doc;

    builder = new SAXBuilder();

    if (resolver != null) {
      builder.setEntityResolver(resolver);
    }

    try {
      if (resolver != null) {
        // WTF?  seems relative entity URIs are allowed
        // by certain xerces impls.  but fully qualified
        // file://... URLs trigger a NullPointerException
        // in others.  setting base here worksaround
        doc = builder.build(is, "");
      } else {
        doc = builder.build(is);
      }
    } catch (JDOMException exc) {
      XmlParseException toThrow = new XmlParseException(exc.getMessage());
      toThrow.initCause(exc);
      throw toThrow;
    } catch (IOException exc) {
      XmlParseException toThrow = new XmlParseException(exc.getMessage());
      toThrow.initCause(exc);
      throw toThrow;
    }

    generalParse(tag, doc);
  }