Java 类org.jdom.input.SAXBuilder 实例源码

项目:spicy    文件:DAOXmlUtility.java   
public org.jdom.Document buildDOM(String fileName) throws DAOException {
    if (fileName == null || "".equals(fileName)) {
        throw new DAOException("Unable to load file. Null or empty path requested");
    }
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);
    org.jdom.Document document = null;
    try {
        fileName = checkFilePath(fileName);
        document = builder.build(fileName);
        return document;
    } catch (org.jdom.JDOMException jde) {
        logger.error(jde);
        throw new DAOException(jde.getMessage());
    } catch (java.io.IOException ioe) {
        logger.error(ioe);
        throw new DAOException(ioe.getMessage());
    }
}
项目:xstream    文件:JDomReaderTest.java   
public void testCanReadFromElementOfLargerDocument() throws Exception {
    String xml ="" +
            "<big>" +
            "  <small>" +
            "    <tiny/>" +
            "  </small>" +
            "  <small-two>" +
            "  </small-two>" +
            "</big>";
    Document document = new SAXBuilder().build(new StringReader(xml));
    Element element = document.getRootElement().getChild("small");

    HierarchicalStreamReader xmlReader = new JDomReader(element);
    assertEquals("small", xmlReader.getNodeName());
    xmlReader.moveDown();
    assertEquals("tiny", xmlReader.getNodeName());
}
项目:sumo    文件:H2Fetcher.java   
public static void addImagePlanning(String dbname, File planningFile) throws Exception {
    // create xml reader
    SAXBuilder builder = new SAXBuilder();
    Document doc;
    doc = builder.build(planningFile);
    Element atts = doc.getRootElement();
    // check format first
    if (atts.getName().equalsIgnoreCase("imageplanning")) {
        // connect to database
        Connection conn = DriverManager.getConnection("jdbc:h2:~/.sumo/" + dbname + ";AUTO_SERVER=TRUE", "sa", "");
        Statement stat = conn.createStatement();
        String sql = "create table if not exists IMAGEPLAN (IMAGE VARCHAR(255), URL VARCHAR(1024), STARTDATE VARCHAR(255), ENDDATE VARCHAR(255), AREA VARCHAR(1024), ACTION VARCHAR(2048))";
        stat.execute(sql);
        // clear table before filling it in
        stat.execute("DELETE FROM IMAGEPLAN");
        // scan through images
        for (Object o : atts.getChildren("Image")) {
            Element element = (Element) o;
            // create sql statement
            sql = "INSERT INTO IMAGEPLAN VALUES('" + element.getChildText("name") + "', '" + element.getChildText("url") + "', '" + element.getChildText("startDate") + "', '" + element.getChildText("endDate") + "', '" + element.getChildText("area") + "', '" + element.getChildText("action") + "');";
            stat.execute(sql);
        }
        stat.close();
        conn.close();
    } else {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JOptionPane.showMessageDialog(null, "Format not supported", "Error", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

}
项目:sumo    文件:Radarsat2Image.java   
@Override
public boolean initialise() {
    try {
        super.imgName=manifestFile.getParentFile().getName();

        SAXBuilder builder = new SAXBuilder();
        setFile(manifestFile);
        doc = builder.build(productxml);
        tiffImages = getImages();
        if(tiffImages==null) return false;

        IReader image = tiffImages.values().iterator().next();

        this.displayName=super.imgName;//+ "  " +image.getImageFile().getName();

        parseProductXML(productxml);

        bounds = new Rectangle(0, 0, image.getxSize(), image.getySize());
        readPixel(0,0,0);
    } catch (Exception ex) {
        dispose();
        logger.error(ex.getMessage(),ex);
        return false;
    }
    return true;
}
项目:sumo    文件:Radarsat2ImageGDAL.java   
@Override
public boolean initialise() {
    try {
        super.imgName=manifestFile.getParentFile().getName();

        SAXBuilder builder = new SAXBuilder();
        setFile(manifestFile);
        doc = builder.build(productxml);
        tiffImages = getImages();
        if(tiffImages==null) return false;

        IReader image = tiffImages.values().iterator().next();

        this.displayName=super.imgName;//+ "  " +image.getImageFile().getName();

        super.parseProductXML(productxml);

        bounds = new Rectangle(0, 0, image.getxSize(), image.getySize());
        readPixel(0,0,0);
    } catch (Exception ex) {
        dispose();
        logger.error(ex.getMessage(),ex);
        return false;
    }
    return true;
}
项目:airsonic    文件:LyricsService.java   
private LyricsInfo parseSearchResult(String xml) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new StringReader(xml));

    Element root = document.getRootElement();
    Namespace ns = root.getNamespace();

    String lyric = StringUtils.trimToNull(root.getChildText("Lyric", ns));
    String song =  root.getChildText("LyricSong", ns);
    String artist =  root.getChildText("LyricArtist", ns);

    return new LyricsInfo(lyric, artist, song);
}
项目:gate-core    文件:AnnotationSchema.java   
/** Creates an AnnotationSchema object from an XSchema file
  * @param anXSchemaURL the URL where to find the XSchema file
  */
public void fromXSchema(URL anXSchemaURL)
            throws ResourceInstantiationException {
  org.jdom.Document jDom = null;
  SAXBuilder saxBuilder = new SAXBuilder(false);
  try {
  try{
    jDom = saxBuilder.build(anXSchemaURL);
  }catch(JDOMException je){
    throw new ResourceInstantiationException(je);
  }
  } catch (java.io.IOException ex) {
    throw new ResourceInstantiationException(ex);
  }
  workWithJDom(jDom);
}
项目:gate-core    文件:AnnotationSchema.java   
/** Creates an AnnotationSchema object from an XSchema file
  * @param anXSchemaInputStream the Input Stream containing the XSchema file
  */
public void fromXSchema(InputStream anXSchemaInputStream)
            throws ResourceInstantiationException {
  org.jdom.Document jDom = null;
  SAXBuilder saxBuilder = new SAXBuilder(false);
  try {
  try{
    jDom = saxBuilder.build(anXSchemaInputStream);
  }catch(JDOMException je){
    throw new ResourceInstantiationException(je);
  }
  } catch (java.io.IOException ex) {
    throw new ResourceInstantiationException(ex);
  }
  workWithJDom(jDom);
}
项目:gate-core    文件:CreoleRegisterImpl.java   
/**
 * Default constructor. Sets up directory files parser. <B>NOTE:</B> only
 * Factory should call this method.
 */
public CreoleRegisterImpl() throws GateException {

  // initialise the various maps

  lrTypes = new HashSet<String>();
  prTypes = new HashSet<String>();
  vrTypes = new LinkedList<String>();
  toolTypes = new HashSet<String>();
  applicationTypes = new HashSet<String>();

  plugins = new LinkedHashSet<Plugin>();

  // construct a SAX parser for parsing the CREOLE directory files
  jdomBuilder = new SAXBuilder(false);
  jdomBuilder.setXMLFilter(new CreoleXmlUpperCaseFilter());

  // read plugin name mappings file
  readPluginNamesMappings();

}
项目:gate-core    文件:UpgradeXGAPP.java   
public static void main(String[] args) throws Exception {

    URL input = (new File(
        "/home/mark/gate-top/externals/gate-svn/plugins/Lang_French/french.gapp"))
            .toURI().toURL();

    SAXBuilder builder = new SAXBuilder(false);
    Document doc = builder.build(input);
    List<UpgradePath> upgrades = suggest(doc);
    for(UpgradePath upgrade : upgrades) {
      System.out.println(upgrade);
    }

    upgrade(doc, upgrades);

    outputter.output(doc, System.out);
  }
项目:teamcity-msteams-notifier    文件:MsTeamsNotificationSettingsTest.java   
@SuppressWarnings("unchecked")
@Test
public void test_WebookConfig() throws JDOMException, IOException{
    SAXBuilder builder = new SAXBuilder();
    List<MsTeamsNotificationConfig> configs = new ArrayList<MsTeamsNotificationConfig>();
    builder.setIgnoringElementContentWhitespace(true);
        Document doc = builder.build("src/test/resources/testdoc2.xml");
        Element root = doc.getRootElement();
        if(root.getChild("msteamsNotifications") != null){
            Element child = root.getChild("msteamsNotifications");
            if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))){
                List<Element> namedChildren = child.getChildren("msteamsNotification");
                for(Iterator<Element> i = namedChildren.iterator(); i.hasNext();)
                {
                    Element e = i.next();
                    MsTeamsNotificationConfig whConfig = new MsTeamsNotificationConfig(e);
                    configs.add(whConfig);
                }
            }
        }


    for (MsTeamsNotificationConfig c : configs){
        MsTeamsNotification wh = new MsTeamsNotificationImpl();
        wh.setEnabled(c.getEnabled());
        //msteamsNotification.addParams(c.getParams());
        System.out.println(wh.isEnabled().toString());

    }
}
项目:teamcity-msteams-notifier    文件:MsTeamsNotificationSettingsTest.java   
@SuppressWarnings("unchecked")
@Test
public void test_ReadXml() throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    //builder.setValidation(true);
    builder.setIgnoringElementContentWhitespace(true);

        Document doc = builder.build("src/test/resources/testdoc1.xml");
        Element root = doc.getRootElement();
        System.out.println(root.toString());
        if(root.getChild("msteamsNotifications") != null){
            Element child = root.getChild("msteamsNotifications");
            if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))){
                List<Element> namedChildren = child.getChildren("msteamsNotification");
                for(Iterator<Element> i = namedChildren.iterator(); i.hasNext();)
                {
                    Element e = i.next();
                    System.out.println(e.toString() + e.getAttributeValue("url"));
                    //assertTrue(e.getAttributeValue("url").equals("http://something"));
                    if(e.getChild("parameters") != null){
                        Element eParams = e.getChild("parameters");
                        List<Element> paramsList = eParams.getChildren("param");
                        for(Iterator<Element> j = paramsList.iterator(); j.hasNext();)
                        {
                            Element eParam = j.next();
                            System.out.println(eParam.toString() + eParam.getAttributeValue("name"));
                            System.out.println(eParam.toString() + eParam.getAttributeValue("value"));
                        }
                    }
                }
            }
        }

}
项目:educational-plugin    文件:EduBuiltInServerUtils.java   
@Nullable
private static Element readComponent(@NotNull SAXBuilder parser, @NotNull String projectPath) {
  Element component = null;
  try {
    String studyProjectXML = projectPath + STUDY_PROJECT_XML_PATH;
    Document xmlDoc = parser.build(new File(studyProjectXML));
    Element root = xmlDoc.getRootElement();
    component = root.getChild("component");
  }
  catch (JDOMException | IOException ignored) {
  }

  return component;
}
项目:lvm4j    文件:File.java   
/**
 * Parse the parameters of an markovmodel.xml file for an HMM object as HMMParams object.
 *
 * @param hmmFile the string to the markovmodel file
 * @return a HMMParams object containing all relevant parameters for the HMM
 */
public static HMMParams parseXML(java.lang.String hmmFile)
{
    HMMParams params = HMMParams.newInstance();
    SAXBuilder builder = new SAXBuilder();
    Document document;
    try
    {
        _LOGGER.info("Parsing markovmodel xml.");
        document = builder.build(hmmFile);
        setStandardParams(document, params);
        setTrainingParams(document, params);
    }
    catch (IOException | JDOMException e)
    {
        _LOGGER.error("Could not open file: " + e.getMessage());
    }
    return params;
}
项目:OSCAR-ConCert    文件:OntarioMD.java   
private Hashtable parseReturn(InputStream is){
    Hashtable h = null;
    try {


        SAXBuilder parser = new SAXBuilder();
        Document doc = parser.build(is);
        Element root = doc.getRootElement();
         h  = new Hashtable();
        String jsessionID =g(root.getDescendants(new ElementFilter("jsessionID")));
        String ptLoginToken =g(root.getDescendants(new ElementFilter("ptLoginToken")));
        String returnCode =g(root.getDescendants(new ElementFilter("returnCode")));

        h.put("returnCode",returnCode);
        h.put("ptLoginToken",ptLoginToken);
        h.put("jsessionID",jsessionID);

    }catch(Exception e){
        MiscUtils.getLogger().error("Error", e);
    }
    return h;
}
项目:gemfirexd-oss    文件:MarketUpdate.java   
public MarketUpdate ( String xml, boolean isNew ) {

    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        Reader string_reader = new StringReader(xml);
        doc = builder.build(string_reader);
    } catch (Exception e) {
        System.out.println("Caught exception during XML parsing of a Trade");
        e.printStackTrace();
    }

    Element root_element = doc.getRootElement ();
    this.ccy          = getStringElement(root_element, "ccy");
    this.ValueDate        = getStringElement(root_element, "ValueDate");
    this.value          = getDoubleElement(root_element, "value");
    this.spot           = getDoubleElement(root_element, "spot");
    this.discount_factor    = getDoubleElement(root_element, "discount_factor");

    this.tickId         = getIntegerElement(root_element, "TickId" );
    //this.wanIdentity = wanIdentity;
    this.isNew = isNew;
  }
项目:TalkAndPlay    文件:XMLConfigurationHandler.java   
/**
 * Parse the XML file that holds all users' configuration
 *
 * @return
 * @throws Exception
 */
private void parseXML(File file) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    configurationXmlDocument = (Document) builder.build(file);

    userFiles = new HashMap();
    users = new ArrayList();
    List usersEl = configurationXmlDocument.getRootElement().getChildren();

    for (int i = 0; i < usersEl.size(); i++) {
        imageAndSoundFilePaths = new ArrayList();
        User user = parseUserFromXml((Element) usersEl.get(i));
        currentUser = user;
        users.add(user);
        userFiles.put(user.getName(), imageAndSoundFilePaths);
    }
}
项目:TalkAndPlay    文件:Properties.java   
public Properties() {
    try {
        String encodedApplicationFolder = (new File(Properties.class
                .getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())).getParentFile().getAbsolutePath();
        applicationFolder = URLDecoder.decode(encodedApplicationFolder, "UTF-8");

        File file = new File(applicationFolder, "properties.xml");
        if (!file.exists()) {
            file = new File("properties.xml");
        }
        SAXBuilder builder = new SAXBuilder();
        configurationFile = builder.build(file);
        parseXML();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
项目:TalkAndPlay    文件:GameService.java   
public List setDefaultGames() {
    List games = null;
    try {
        String filePath = System.getProperty("user.dir") + File.separator + "defaultGames.xml";
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
            return games;
        }

        SAXBuilder builder = new SAXBuilder();
        Document configurationFile = (Document) builder.build(file);

        games = configurationFile.getRootElement().getChildren();

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    return games;
}
项目:TalkAndPlay    文件:UserService.java   
/**
 * Upload a user from xml file
 *
 * @param file
 */
public boolean uploadUserFromFile(File file) {
    try {
        //get profile from selected file
        SAXBuilder builder = new SAXBuilder();
        Document profileXml = (Document) builder.build(file);
        Element profile = profileXml.getRootElement();
        profile.detach();
        //check if profile name is unique
        List<User> users = talkAndPlayProfileconfiguration.getConfigurationHandler().getUsers();
        String name = profile.getChild("name").getText();
        if (nameIsUsed(name)) {
            profile.getChild("name").setText(getUniqueUserName(name, users));
        }
        Element profiles = talkAndPlayProfileconfiguration.getConfigurationHandler().getRootElement();
        profiles.addContent(profile);
        talkAndPlayProfileconfiguration.getConfigurationHandler().update();
    } catch (Exception ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}
项目:powermock-examples-maven    文件:StaticWithJdomTest.java   
@org.junit.Test
public void test() throws Exception {

    PowerMock.mockStatic(StaticClass.class);
    EasyMock.expect(StaticClass.staticMethod()).andReturn(2).anyTimes();
    PowerMock.replay(StaticClass.class);

    int i = StaticClass.staticMethod();

    String xml = "<xml>" + i + "</xml>";
    SAXBuilder b = new SAXBuilder();

    Document d = b.build(new StringReader(xml));
    Assert.assertTrue(d.getRootElement().getText().equals("2"));
    PowerMock.verify(StaticClass.class);
}
项目:My-Javaweb-Homework    文件:XMLInputUtil.java   
public List<StudentEntity> getData(){
    List<StudentEntity> students = new ArrayList<StudentEntity>();
    SAXBuilder builder = new SAXBuilder();
       try {
        Document doc = builder.build(new File(inputPath));
        Element rootEl = doc.getRootElement();
        List<Element> list = rootEl.getChildren("student");
        for (Element el : list) {
            StudentEntity student = new StudentEntity();
            student.setClassName(el.getChildText("classname"));
            student.setGender(el.getChildText("gender"));
            student.setGrade(el.getChildText("grade"));
            student.setMajor(el.getChildText("major"));
            student.setStudentName(el.getChildText("studentname"));
            student.setStudentNumber(el.getChildText("studentnumber"));
            students.add(student);
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
    return students;
}
项目:zap-maven-plugin    文件:AlertsFile.java   
public static List<Alert> getAlertsFromFile(File file, String alertType) throws JDOMException, IOException {
    List<Alert> alerts =  new ArrayList<>();
    SAXBuilder parser = new SAXBuilder();
    Document alertsDoc = parser.build(file);
    @SuppressWarnings("unchecked")
    List<Element> alertElements = alertsDoc.getRootElement().getChildren(alertType);
    for (Element element: alertElements){
        Alert alert = new Alert(
                element.getAttributeValue("alert"),
                element.getAttributeValue("url"),
                element.getAttributeValue("risk"),
                element.getAttributeValue("confidence"),
                element.getAttributeValue("param"),
                element.getAttributeValue("other"));
        alerts.add(alert);
    }
    return alerts;
}
项目:pathvisio    文件:VisualizationManager.java   
public  Document getXML() {
    InputStream in = getXmlInput();
    Document doc;
    Element root;
    try {
        SAXBuilder parser = new SAXBuilder();
        doc = parser.build(in);
        in.close();
        root = doc.getRootElement();
    } catch(Exception e) {
        doc = new Document();
        root = new Element(ROOT_XML_ELEMENT);
        doc.setRootElement(root);
    }
    return doc;
}
项目:intellij-ce-playground    文件:JiraLegacyApi.java   
private List<Task> processRSS(@NotNull GetMethod method) throws Exception {
  // Basic authorization should be enough
  int code = myRepository.getHttpClient().executeMethod(method);
  if (code != HttpStatus.SC_OK) {
    throw new Exception(TaskBundle.message("failure.http.error", code, method.getStatusText()));
  }
  Element root = new SAXBuilder(false).build(method.getResponseBodyAsStream()).getRootElement();
  Element channel = root.getChild("channel");
  if (channel != null) {
    List<Element> children = channel.getChildren("item");
    LOG.debug("Total issues in JIRA RSS feed: " + children.size());
    return ContainerUtil.map(children, new Function<Element, Task>() {
      public Task fun(Element element) {
        return new JiraSoapTask(element, myRepository);
      }
    });
  }
  else {
    LOG.warn("JIRA channel not found");
  }
  return ContainerUtil.emptyList();
}
项目:intellij-ce-playground    文件:YouTrackRepository.java   
HttpMethod doREST(String request, boolean post) throws Exception {
  HttpClient client = login(new PostMethod(getUrl() + "/rest/user/login"));
  String uri = getUrl() + request;
  HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
  configureHttpMethod(method);
  int status = client.executeMethod(method);
  if (status == 400) {
    InputStream string = method.getResponseBodyAsStream();
    Element element = new SAXBuilder(false).build(string).getRootElement();
    TaskUtil.prettyFormatXmlToLog(LOG, element);
    if ("error".equals(element.getName())) {
      throw new Exception(element.getText());
    }
  }
  return method;
}
项目:intellij-ce-playground    文件:YouTrackIntellisense.java   
public Response(@NotNull InputStream stream) throws Exception {
  final Element root = new SAXBuilder().build(stream).getRootElement();
  TaskUtil.prettyFormatXmlToLog(LOG, root);
  @NotNull final Element highlight = root.getChild("highlight");
  //assert highlight != null : "no '/IntelliSense/highlight' element in YouTrack response";
  myHighlightRanges = ContainerUtil.map(highlight.getChildren("range"), new Function<Element, HighlightRange>() {
    @Override
    public HighlightRange fun(Element range) {
      return new HighlightRange(range);
    }
  });

  @NotNull final Element suggest = root.getChild("suggest");
  //assert suggest != null : "no '/IntelliSense/suggest' element in YouTrack response";
  myCompletionItems = ContainerUtil.map(suggest.getChildren("item"), new Function<Element, CompletionItem>() {
    @Override
    public CompletionItem fun(Element item) {
      return new CompletionItem(item);
    }
  });
}
项目:intellij-ce-playground    文件:PivotalTrackerRepository.java   
private List<Element> getStories(@Nullable final String query, final int max) throws Exception {
  String url = API_URL + "/projects/" + myProjectId + "/stories";
  url += "?filter=" + encodeUrl("state:started,unstarted,unscheduled,rejected");
  if (!StringUtil.isEmpty(query)) {
    url += encodeUrl(" \"" + query + '"');
  }
  if (max >= 0) {
    url += "&limit=" + encodeUrl(String.valueOf(max));
  }
  LOG.info("Getting all the stories with url: " + url);
  final HttpMethod method = doREST(url, HTTPMethod.GET);
  final InputStream stream = method.getResponseBodyAsStream();
  final Element element = new SAXBuilder(false).build(stream).getRootElement();

  if (!"stories".equals(element.getName())) {
    LOG.warn("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode());
    throw new Exception("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode() +
                        "\n" + element.getText());
  }

  return element.getChildren("story");
}
项目:intellij-ce-playground    文件:Palette.java   
private void upgradePalette() {
  // load new components from the predefined Palette2.xml
  try {
    //noinspection HardCodedStringLiteral
    Document document = new SAXBuilder().build(getClass().getResourceAsStream("/idea/Palette2.xml"));
    for (Element groupElement : document.getRootElement().getChildren(ELEMENT_GROUP)) {
      for (GroupItem group : myGroups) {
        if (group.getName().equals(groupElement.getAttributeValue(ATTRIBUTE_NAME))) {
          upgradeGroup(group, groupElement);
          break;
        }
      }
    }
  }
  catch (Exception e) {
    LOG.error(e);
  }
}
项目:mars-sim    文件:UIConfig.java   
/**
 * Loads and parses the XML save file.
 */
public void parseFile() {
    FileInputStream stream = null;

    try {
        /* [landrus, 27.11.09]: Hard paths are a pain with webstart, so we will use the users home dir,
         * because this will work properly. */
        stream = new FileInputStream(new File(DIRECTORY, FILE_NAME));
        /* bug 2909888: read the inputstream with a specific encoding instead of the system default. */
        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
        SAXBuilder saxBuilder = new SAXBuilder(true);
        configDoc = saxBuilder.build(reader);
    } catch (Exception e) {
        if(!(e instanceof FileNotFoundException))
            logger.log(Level.SEVERE, "parseFile()", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}
项目:tibco-bwmaven    文件:IncludeDependenciesInEARMojo.java   
private void updateAlias(String includeOrigin, String includeDestination, File ear) throws JDOMException, IOException, JDOMException {
    TFile xmlTIBCO = new TFile(ear.getAbsolutePath() + File.separator + "TIBCO.xml");
    String tempPath = ear.getParentFile().getAbsolutePath() + File.separator + "TIBCO.xml";
    TFile xmlTIBCOTemp = new TFile(tempPath);

    truezip.copyFile(xmlTIBCO, xmlTIBCOTemp);

    File xmlTIBCOFile = new File(tempPath);

    SAXBuilder sxb = new SAXBuilder();
    Document document = sxb.build(xmlTIBCOFile);

    XPath xpa = XPath.newInstance("//dd:NameValuePairs/dd:NameValuePair[starts-with(dd:name, 'tibco.alias') and dd:value='" + includeOrigin + "']/dd:value");
    xpa.addNamespace("dd", "http://www.tibco.com/xmlns/dd");

    Element singleNode = (Element) xpa.selectSingleNode(document);
    if (singleNode != null) {
        singleNode.setText(includeDestination);
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat().setIndent("    "));
        xmlOutput.output(document, new FileWriter(xmlTIBCOFile));

        truezip.copyFile(xmlTIBCOTemp, xmlTIBCO);
    }

    updateAliasInPARs(includeOrigin, includeDestination, ear);
}
项目:tibco-bwmaven    文件:IncludeDependenciesInEARMojo.java   
private void updateAliasInPARs(String includeOrigin, String includeDestination, File ear) throws IOException, JDOMException {
    TrueZipFileSet pars = new TrueZipFileSet();
    pars.setDirectory(ear.getAbsolutePath());
    pars.addInclude("*.par");
    List<TFile> parsXML = truezip.list(pars);
    for (TFile parXML : parsXML) {
        TFile xmlTIBCO = new TFile(parXML, "TIBCO.xml");

        String tempPath = ear.getParentFile().getAbsolutePath() + File.separator + "TIBCO.xml";
        TFile xmlTIBCOTemp = new TFile(tempPath);

        truezip.copyFile(xmlTIBCO, xmlTIBCOTemp);

        File xmlTIBCOFile = new File(tempPath);

        SAXBuilder sxb = new SAXBuilder();
        Document document = sxb.build(xmlTIBCOFile);

        XPath xpa = XPath.newInstance("//dd:NameValuePairs/dd:NameValuePair[dd:name='EXTERNAL_JAR_DEPENDENCY']/dd:value");
        xpa.addNamespace("dd", "http://www.tibco.com/xmlns/dd");

        Element singleNode = (Element) xpa.selectSingleNode(document);
        if (singleNode != null) {
            String value = singleNode.getText().replace(includeOrigin, includeDestination);
            singleNode.setText(value);
            XMLOutputter xmlOutput = new XMLOutputter();
            xmlOutput.setFormat(Format.getPrettyFormat().setIndent("    "));
            xmlOutput.output(document, new FileWriter(xmlTIBCOFile));

            truezip.copyFile(xmlTIBCOTemp, xmlTIBCO);
        }
    }
}
项目:Tank    文件:GenericXMLHandler.java   
/**
 * Constructor
 * 
 * @param xmlFile
 *            The string representation of the xml data
 */
public GenericXMLHandler(String xmlFile) {
    if (StringUtils.isNotEmpty(xmlFile)) {
        this.xml = xmlFile;
        try {
            this.xmlFile = null;
            this.xmlDocument = new org.jdom.Document();
            SAXBuilder builder = new SAXBuilder();
            builder.setValidation(false);
            // LOG.debug("XML string to load: "+xmlFile);
            xmlFile = xmlFile.substring(xmlFile.indexOf("<"));
            this.xmlDocument = builder.build(new StringReader(xmlFile));
            this.namespaces = new HashMap<String, String>();
            InputSource is = new InputSource(new StringReader(xml));
            this.dDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(is);
        } catch (Exception ex) {
            this.xmlDocument = null;
            LOG.error("Error parsing xml Response: " + xmlFile + ": " + ex.getMessage());
        }
    }
}
项目:eurocarbdb    文件:Config.java   
@SuppressWarnings("unchecked")
public void readConfigFile(String filename) throws ResourcesDbException {
    SAXBuilder parser = new SAXBuilder();
    try {
        Document doc = parser.build(filename);
        org.jdom.Element root = doc.getRootElement();
        //listChildren(root, 0);
        List configList = root.getChildren();
        Iterator configIter = configList.iterator();
        while(configIter.hasNext()) {
            org.jdom.Element xmlElement = (org.jdom.Element) configIter.next();
            if(xmlElement.getName().equals("file_locations")) {
            } else if(xmlElement.getName().equals("residue_parsing")) {
                parseResidueParsingPart(xmlElement);
            } else if(xmlElement.getName().equals("residue_name_generation")) {
                parseResidueNameGenerationPart(xmlElement);
            }
        }
    } catch (JDOMException je) {
        System.out.println("JDOMException: " + je.getMessage());
        throw new ResourcesDbException("Error reading config file: " + je.getMessage());
    } catch (IOException ie) {
        System.out.println("IOException: " + ie.getMessage());
        throw new ResourcesDbException("Error reading config file: " + ie.getMessage());
    }  
}
项目:eurocarbdb    文件:TrivialnameTemplateContainer.java   
private ArrayList<TrivialnameTemplate> getTemplateListFromXml(URL xmlUrl) throws ResourcesDbException {
    ArrayList<TrivialnameTemplate> tmplList = new ArrayList<TrivialnameTemplate>();
    SAXBuilder parser = new SAXBuilder();
    try {
        Document doc = parser.build(xmlUrl);
        org.jdom.Element root = doc.getRootElement();
        List<?> templateTagsList = root.getChildren();
        Iterator<?> templatesIter = templateTagsList.iterator();
        while(templatesIter.hasNext()) {
            org.jdom.Element xmlTemplate = (org.jdom.Element) templatesIter.next();
            TrivialnameTemplate template = getTemplateFromXmlTree(xmlTemplate);
            if(template != null) {
                tmplList.add(template);
            }
        }
    } catch (JDOMException je) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", je);
    } catch (IOException ie) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", ie);
    }  
    return tmplList;
}
项目:eurocarbdb    文件:AglyconTemplateContainer.java   
public ArrayList<AglyconTemplate> readTemplatesFromXmlFile(URL xmlUrl) throws ResourcesDbException {
    ArrayList<AglyconTemplate> tmplList = new ArrayList<AglyconTemplate>();
    SAXBuilder parser = new SAXBuilder();
    try {
        Document doc = parser.build(xmlUrl);
        org.jdom.Element root = doc.getRootElement();
        List<?> templateList = root.getChildren();
        Iterator<?> templatesIter = templateList.iterator();
        while(templatesIter.hasNext()) {
            org.jdom.Element xmlTemplate = (org.jdom.Element) templatesIter.next();
            AglyconTemplate template = getTemplateFromXmlTree(xmlTemplate);
            if(template != null) {
                //System.out.println("Template: " + template.toString());
                tmplList.add(template);
            }
        }
    } catch (JDOMException je) {
        throw new ResourcesDbException("Exception in setting aglycon template data from xml file.", je);
    } catch (IOException ie) {
        throw new ResourcesDbException("Exception in setting aglycon template data from xml file.", ie);
    }  
    return tmplList;
}
项目:eurocarbdb    文件:MonosaccharideDictionary.java   
private void fillMap(URL xmlUrl) throws ResourcesDbException {
    SAXBuilder parser = new SAXBuilder();
    try {
        Document doc = parser.build(xmlUrl);
        org.jdom.Element root = doc.getRootElement();
        List<?> xmlTemplateList = root.getChildren();
        Iterator<?> templatesIter = xmlTemplateList.iterator();
        while(templatesIter.hasNext()) {
            org.jdom.Element xmlEntry = (org.jdom.Element) templatesIter.next();
            try {
                MonosaccharideDictionaryEntry entry = getEntryFromXmlTree(xmlEntry);
                //System.out.println(entry);
                if(entry != null) {
                    this.addEntry(entry);
                }
            } catch(ResourcesDbException rEx) {
                System.err.println(rEx);
            }
        }
    } catch (JDOMException je) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", je);
    } catch (IOException ie) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", ie);
    }
}
项目:eurocarbdb    文件:SubstituentTemplateContainer.java   
private static ArrayList<SubstituentTemplate> getTemplateListFromXml(URL xmlUrl) throws ResourcesDbException {
    SAXBuilder parser = new SAXBuilder();
    ArrayList<SubstituentTemplate> templateList = new ArrayList<SubstituentTemplate>();
    try {
        Document doc = parser.build(xmlUrl);
        org.jdom.Element root = doc.getRootElement();
        List<?> xmlTemplateList = root.getChildren();
        Iterator<?> templatesIter = xmlTemplateList.iterator();
        while(templatesIter.hasNext()) {
            org.jdom.Element xmlTemplate = (org.jdom.Element) templatesIter.next();
            SubstituentTemplate template = getTemplateFromXmlTree(xmlTemplate);
            if(template != null) {
                templateList.add(template);
            }
        }
    } catch (JDOMException je) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", je);
    } catch (IOException ie) {
        throw new ResourcesDbException("Exception in reading TrivialnameTemplate XML file.", ie);
    }  
    return templateList;
}
项目:RealmSpeak    文件:RealmCharacterWebFrame.java   
public boolean loadFromStream(InputStream stream) {
    try {
        // Load file
        Document doc = new SAXBuilder().build(stream);

        // Read layout
        Element layout = doc.getRootElement();
        List list = layout.getChildren();
        for (Iterator i=list.iterator();i.hasNext();) {
            Element rschar = (Element)i.next();
            RscharLayout rl = new RscharLayout(characterFolder,rschar);
            layoutRecords.add(rl);
            if (rscharFiles.contains(rl.getFile())) {
                rscharFiles.remove(rl.getFile());
            }
        }
        return true;
    }
    catch(Exception ex) {
        JOptionPane.showMessageDialog(null,"Invalid file/format:\n\n"+ex,"Error",JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    }
    return false;
}
项目:powermock    文件:StaticWithJdomTest.java   
@org.junit.Test
public void test() throws Exception {

    PowerMock.mockStatic(StaticClass.class);
    EasyMock.expect(StaticClass.staticMethod()).andReturn(2).anyTimes();
    PowerMock.replay(StaticClass.class);

    int i = StaticClass.staticMethod();

    String xml = "<xml>" + i + "</xml>";
    SAXBuilder b = new SAXBuilder();

    Document d = b.build(new StringReader(xml));
    Assert.assertTrue(d.getRootElement().getText().equals("2"));
    PowerMock.verify(StaticClass.class);
}