Java Code Examples for org.jdom2.input.SAXBuilder#build()

The following examples show how to use org.jdom2.input.SAXBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MCRDynamicURIResolver.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected Element getRootElement() {
    if (cachedElement == null || xmlFile.lastModified() > lastModified) {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(xmlFile);
            cachedElement = doc.getRootElement();
            lastModified = System.currentTimeMillis();
        } catch (Exception exc) {
            LOGGER.error("Error while parsing {}!", xmlFile, exc);
            return null;
        }
    }
    // clone it for further replacements
    // TODO: whats faster? cloning or building it new from file
    return cachedElement.clone();
}
 
Example 2
Source File: InvCatalogFactory.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create an InvCatalog by reading catalog XML from a StringReader.
 *
 * Failures and exceptions are handled by causing validate() to
 * fail. Therefore, be sure to call validate() before trying to use
 * the InvCatalog object.
 *
 * @param catAsStringReader : the StreamReader from which to read the catalog.
 * @param baseUri : the base URI of the document, used for resolving reletive references.
 * @return an InvCatalogImpl object
 */
public InvCatalogImpl readXML(StringReader catAsStringReader, URI baseUri) {
  XMLEntityResolver resolver = new XMLEntityResolver(false);
  SAXBuilder builder = resolver.getSAXBuilder();

  Document inDoc;
  try {
    inDoc = builder.build(catAsStringReader);
  } catch (Exception e) {
    InvCatalogImpl cat = new InvCatalogImpl(baseUri.toString(), null, null);
    cat.appendErrorMessage(
        "**Fatal:  InvCatalogFactory.readXML(String catAsString, URI url) failed:" + "\n  Exception= "
            + e.getClass().getName() + " " + e.getMessage() + "\n  fatalMessages= " + fatalMessages.toString()
            + "\n  errMessages= " + errMessages.toString() + "\n  warnMessages= " + warnMessages.toString() + "\n",
        true);
    return cat;
  }

  return readXML(inDoc, baseUri);
}
 
Example 3
Source File: Atom10Parser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Parse entry from reader.
 */
public static Entry parseEntry(final Reader rd, final String baseURI, final Locale locale) throws JDOMException, IOException, IllegalArgumentException,
        FeedException {

    // Parse entry into JDOM tree
    final SAXBuilder builder = new SAXBuilder();
    final Document entryDoc = builder.build(rd);
    final Element fetchedEntryElement = entryDoc.getRootElement();
    fetchedEntryElement.detach();

    // Put entry into a JDOM document with 'feed' root so that Rome can
    // handle it
    final Feed feed = new Feed();
    feed.setFeedType("atom_1.0");
    final WireFeedOutput wireFeedOutput = new WireFeedOutput();
    final Document feedDoc = wireFeedOutput.outputJDom(feed);
    feedDoc.getRootElement().addContent(fetchedEntryElement);

    if (baseURI != null) {
        feedDoc.getRootElement().setAttribute("base", baseURI, Namespace.XML_NAMESPACE);
    }

    final WireFeedInput input = new WireFeedInput(false, locale);
    final Feed parsedFeed = (Feed) input.build(feedDoc);
    return parsedFeed.getEntries().get(0);
}
 
Example 4
Source File: WhiteTextCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {

    try {
        if (corpus == null) {
            corpus = CorporaHelper.CORPORA_HOME
                    + "/src/main/resources/pear_resources/whitetext/WhiteText.1.3.xml";
        }
        checkArgument(new File(corpus).exists());
        InputStream corpusIs = new FileInputStream(corpus);

        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(corpusIs);
        Element rootNode = doc.getRootElement();

        articleIt = rootNode.getChildren("PubmedArticle").iterator();

    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceConfigurationException.NONEXISTENT_PARAMETER,
                new Object[] { corpus });
    }
}
 
Example 5
Source File: XMLUtil.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
public static List readNodeStore(File orgfile) {
    List<Element> returnElement=new LinkedList<Element>();
    try {
        boolean validate = false;
        SAXBuilder builder = new SAXBuilder(validate);
        InputStream in =new FileInputStream(orgfile);
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        // 获取根节点 <university>
        for(Element  element: root.getChildren()){
            List<Element> childElement= element.getChildren();
            for(Element tmpele:childElement){
                returnElement.add(tmpele);
            }

        }
        return returnElement;
        //readNode(root, "");
    } catch (Exception e) {
        LOGGER.error(e.getMessage(),e);
    }
    return returnElement;
}
 
Example 6
Source File: DomainConfigTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDomainConfig() throws Exception {

    URL resurl = DomainConfigTest.class.getResource("/domain.xml");
    SAXBuilder jdom = new SAXBuilder();
    Document doc = jdom.build(resurl);

    ConfigContext context = ConfigSupport.createContext(null, Paths.get(resurl.toURI()), doc);
    ConfigPlugin plugin = new WildFlyCamelConfigPlugin();
    plugin.applyDomainConfigChange(context, true);

    Element element = ConfigSupport.findChildElement(doc.getRootElement(), "server-groups", NS_DOMAINS);
    Assert.assertNotNull("server-groups not null", element);
    element = ConfigSupport.findElementWithAttributeValue(element, "server-group", "name", "camel-server-group", NS_DOMAINS);
    Assert.assertNotNull("camel-server-group not null", element);

    XMLOutputter output = new XMLOutputter();
    output.setFormat(Format.getRawFormat());
    //System.out.println(output.outputString(doc));
}
 
Example 7
Source File: TestExtractionTest.java    From emissary with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void testCheckStringValueForCollectionFailure() throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder(org.jdom2.input.sax.XMLReaders.NONVALIDATING);
    String resourceName = "/emissary/test/core/TestExtractionTest.xml";
    InputStream inputStream = TestExtractionTest.class.getResourceAsStream(resourceName);
    Assert.assertNotNull("Could not locate: " + resourceName, inputStream);
    Document answerDoc = builder.build(inputStream);
    inputStream.close();

    WhyDoYouMakeMeDoThisExtractionTest test = new WhyDoYouMakeMeDoThisExtractionTest("nonsense");

    Element meta = answerDoc.getRootElement().getChild("answers").getChild("meta");
    test.checkStringValue(meta, "7;0;0;0;2;1", "testCheckStringValueForCollection");

}
 
Example 8
Source File: XMLUtil.java    From jframe with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map doXMLParse(String strxml) throws JDOMException,
        IOException {
    strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

    if (null == strxml || "".equals(strxml)) {
        return null;
    }

    Map m = new HashMap();

    InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(in);
    Element root = doc.getRootElement();
    List list = root.getChildren();
    Iterator it = list.iterator();
    while (it.hasNext()) {
        Element e = (Element) it.next();
        String k = e.getName();
        String v = "";
        List children = e.getChildren();
        if (children.isEmpty()) {
            v = e.getTextNormalize();
        } else {
            v = XMLUtil.getChildrenText(children);
        }

        m.put(k, v);
    }

    in.close();

    return m;
}
 
Example 9
Source File: MCRTransferPackageUtil.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Imports a derivate from the given target directory path.
 * 
 * @param targetDirectory path to the extracted *.tar archive
 * @param derivateId the derivate to import
 * @throws JDOMException derivate xml couldn't be read
 * @throws IOException some file system stuff went wrong
 * @throws MCRAccessException you do not have the permissions to do the import
 */
public static void importDerivate(Path targetDirectory, String derivateId)
    throws JDOMException, IOException, MCRAccessException {
    SAXBuilder sax = new SAXBuilder();

    Path derivateDirectory = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(derivateId);
    Path derivatePath = derivateDirectory.resolve(derivateId + ".xml");

    LOGGER.info("Importing {}", derivatePath.toAbsolutePath().toString());
    MCRDerivate der = new MCRDerivate(sax.build(derivatePath.toFile()));
    MCRMetadataManager.update(der);

    MCRDirectory dir = MCRDirectory.getRootDirectory(der.getId().toString());
    if (dir == null) {
        LOGGER.info("Creating missing {} {}", MCRFilesystemNode.class.getSimpleName(), der.getId());
        dir = new MCRDirectory(der.getId().toString());
    }
    try (Stream<Path> stream = Files.find(derivateDirectory, 5,
        (path, attr) -> !path.toString().endsWith(".md5") && Files.isRegularFile(path) && !path.equals(
            derivatePath))) {
        stream.forEach(path -> {
            String targetPath = derivateDirectory.relativize(path).toString();
            try (InputStream in = Files.newInputStream(path)) {
                Files.copy(in, MCRPath.getPath(derivateId, targetPath), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ioExc) {
                throw new MCRException("Unable to add file " + path.toAbsolutePath() + " to derivate " + derivateId,
                    ioExc);
            }
        });
    }
}
 
Example 10
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Use NCML to modify a dataset, getting the NcML document as a resource stream.
 * Uses ClassLoader.getResourceAsStream(ncmlResourceLocation), so the NcML can be inside of a jar file, for example.
 *
 * @param ncDataset modify this dataset
 * @param ncmlResourceLocation resource location of NcML
 * @param cancelTask allow user to cancel task; may be null
 * @throws IOException on read error
 */
public static void wrapNcMLresource(NetcdfDataset ncDataset, String ncmlResourceLocation, CancelTask cancelTask)
    throws IOException {
  ClassLoader cl = ncDataset.getClass().getClassLoader();
  try (InputStream is = cl.getResourceAsStream(ncmlResourceLocation)) {
    if (is == null)
      throw new FileNotFoundException(ncmlResourceLocation);

    if (debugXML) {
      System.out.println(" NetcdfDataset URL = <" + ncmlResourceLocation + ">");
      try (InputStream is2 = cl.getResourceAsStream(ncmlResourceLocation)) {
        System.out.println(" contents=\n" + IO.readContents(is2));
      }
    }

    org.jdom2.Document doc;
    try {
      SAXBuilder builder = new SAXBuilder();
      if (debugURL)
        System.out.println(" NetcdfDataset URL = <" + ncmlResourceLocation + ">");
      doc = builder.build(is);
    } catch (JDOMException e) {
      throw new IOException(e.getMessage());
    }
    if (debugXML)
      System.out.println(" SAXBuilder done");

    if (showParsedXML) {
      XMLOutputter xmlOut = new XMLOutputter();
      System.out.println("*** NetcdfDataset/showParsedXML = \n" + xmlOut.outputString(doc) + "\n*******");
    }

    Element netcdfElem = doc.getRootElement();

    NcMLReader reader = new NcMLReader();
    reader.readNetcdf(ncDataset.getLocation(), ncDataset, ncDataset, netcdfElem, cancelTask);
    if (debugOpen)
      System.out.println("***NcMLReader.wrapNcML result= \n" + ncDataset);
  }
}
 
Example 11
Source File: SelectiveUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <N > N read(String source, ElementReaderFactory readerFactory) {
    try (Reader stringReader = new StringReader(source)) {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(stringReader);
        Element root = doc.getRootElement();
        return (N) readerFactory.produce(root).read(root);
    } catch (JDOMException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: PersisterTestUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private static Element getRootElement(InputStream xml)
{
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try
    {
        doc = builder.build(xml);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    return doc.getRootElement();
}
 
Example 13
Source File: MCRClassificationMappingEventHandlerTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testMapping() throws SAXParseException, IOException, JDOMException, URISyntaxException {
    MCRSessionMgr.getCurrentSession().isTransactionActive();
    ClassLoader classLoader = getClass().getClassLoader();
    SAXBuilder saxBuilder = new SAXBuilder();

    loadCategory("diniPublType.xml");
    loadCategory("genre.xml");

    Document document = saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + "testMods.xml"));
    MCRObject mcro = new MCRObject();

    MCRMODSWrapper mw = new MCRMODSWrapper(mcro);
    mw.setMODS(document.getRootElement().detach());
    mw.setID("junit", 1);

    MCRClassificationMappingEventHandler mapper = new MCRClassificationMappingEventHandler();
    mapper.handleObjectUpdated(null, mcro);

    String expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'StudyThesis')]";
    XPathExpression<Element> expressionObject = XPathFactory.instance()
        .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    Document xml = mcro.createXML();
    Assert.assertNotNull("The mapped classification should be in the MyCoReObject now!",
        expressionObject.evaluateFirst(
            xml));

    expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'masterThesis')]";
    expressionObject = XPathFactory.instance()
        .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);

    Assert.assertNull("The mapped classification of the child should not be contained in the MyCoReObject now!",
        expressionObject.evaluateFirst(xml));

    LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(xml));
}
 
Example 14
Source File: WmsViewer.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean getCapabilities() {

    Formatter f = new Formatter();
    if (endpoint.indexOf("?") > 0) {
      f.format("%s&request=GetCapabilities&service=WMS&version=%s", endpoint, version);
    } else {
      f.format("%s?request=GetCapabilities&service=WMS&version=%s", endpoint, version);
    }
    System.out.printf("getCapabilities request = '%s'%n", f);
    String url = f.toString();
    info = new Formatter();
    info.format("%s%n", url);

    try (HTTPSession session = HTTPFactory.newSession(url); HTTPMethod method = HTTPFactory.Get(session, url)) {
      int statusCode = method.execute();

      info.format(" Status = %d %s%n", method.getStatusCode(), method.getStatusText());
      info.format(" Status Line = %s%n", method.getStatusLine());
      printHeaders(" Response Headers", method.getResponseHeaders().entries());
      info.format("GetCapabilities:%n%n");

      if (statusCode == 404) {
        throw new FileNotFoundException(method.getPath() + " " + method.getStatusLine());
      }
      if (statusCode >= 300) {
        throw new IOException(method.getPath() + " " + method.getStatusLine());
      }

      SAXBuilder builder = new SAXBuilder();
      Document tdoc = builder.build(method.getResponseAsStream());
      Element root = tdoc.getRootElement();
      parseGetCapabilities(root);
    } catch (Exception e) {
      info.format("%s%n", e.getMessage());
      JOptionPane.showMessageDialog(this, "Failed " + e.getMessage());
      return false;
    }

    return true;
  }
 
Example 15
Source File: XMLConfigProvider.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@Override
public boolean reload() throws Exception
{
    long fileLastModified = file.getContent().getLastModifiedTime();
    if ( fileLastModified== docModified ){
        return false;
    }
    logger.info("Loading config file "+file+", last modified "+fileLastModified+", prev modified "+docModified);
    SAXBuilder jdomBuilder = new SAXBuilder();
    doc = jdomBuilder.build(file.getContent().getInputStream());
    docModified = fileLastModified;
    return true;
}
 
Example 16
Source File: TestRDFXMLSerializer.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void exampleProfileTavernaServer() throws Exception {
	URL tavernaWorkbenc = getClass().getResource("example/profile/tavernaServer.rdf");
	SAXBuilder saxBuilder = new SAXBuilder();
	Document doc = saxBuilder.build(tavernaWorkbenc);
	Element root = doc.getRootElement();

	checkRoot(root);
	checkProfileDocument(root, false);

}
 
Example 17
Source File: XMLFile.java    From Flashtool with GNU General Public License v3.0 4 votes vote down vote up
public XMLFile(File xmlsource) throws IOException, JDOMException {
	SAXBuilder builder = new SAXBuilder();
	document = builder.build(xmlsource);
}
 
Example 18
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Read an NcML file from a URL location, and construct a NetcdfDataset.
 *
 * @param ncmlLocation the URL location string of the NcML document
 * @param referencedDatasetUri if null (usual case) get this from NcML, otherwise use URI as the location of the
 *        referenced dataset.
 * @param cancelTask allow user to cancel the task; may be null
 * @return the resulting NetcdfDataset
 * @throws IOException on read error, or bad referencedDatasetUri URI
 */
public static NetcdfDataset.Builder readNcML(String ncmlLocation, String referencedDatasetUri, CancelTask cancelTask)
    throws IOException {
  URL url = new URL(ncmlLocation);

  if (debugURL) {
    System.out.println(" NcMLReader open " + ncmlLocation);
    System.out.println("   URL = " + url);
    System.out.println("   external form = " + url.toExternalForm());
    System.out.println("   protocol = " + url.getProtocol());
    System.out.println("   host = " + url.getHost());
    System.out.println("   path = " + url.getPath());
    System.out.println("  file = " + url.getFile());
  }

  org.jdom2.Document doc;
  try {
    SAXBuilder builder = new SAXBuilder();
    if (debugURL) {
      System.out.println(" NetcdfDataset URL = <" + url + ">");
    }
    doc = builder.build(url);
  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
  if (debugXML) {
    System.out.println(" SAXBuilder done");
  }

  if (showParsedXML) {
    XMLOutputter xmlOut = new XMLOutputter();
    System.out.println("*** NetcdfDataset/showParsedXML = \n" + xmlOut.outputString(doc) + "\n*******");
  }

  Element netcdfElem = doc.getRootElement();

  if (referencedDatasetUri == null) {
    // the ncml probably refers to another dataset, but doesnt have to
    referencedDatasetUri = netcdfElem.getAttributeValue("location");
    if (referencedDatasetUri == null) {
      referencedDatasetUri = netcdfElem.getAttributeValue("url");
    }
  }
  if (referencedDatasetUri != null) {
    referencedDatasetUri = AliasTranslator.translateAlias(referencedDatasetUri);
  }

  NcMLReaderNew reader = new NcMLReaderNew();
  return reader.readNcML(ncmlLocation, referencedDatasetUri, netcdfElem, cancelTask);
}
 
Example 19
Source File: MCRMetsTestUtil.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
public static Document readXMLFile(String path) throws JDOMException, IOException {
    InputStream resourceAsStream = MCRMetsTestUtil.class.getClassLoader().getResourceAsStream("xml/" + path);
    SAXBuilder builder = new SAXBuilder();
    return builder.build(resourceAsStream);
}
 
Example 20
Source File: TestRDFXMLSerializer.java    From incubator-taverna-language with Apache License 2.0 3 votes vote down vote up
@Test
public void exampleWorkflowBundle() throws Exception {
	URL workflowBundleURL = getClass().getResource("example/workflowBundle.rdf");


	SAXBuilder saxBuilder = new SAXBuilder();
	Document doc = saxBuilder.build(workflowBundleURL);

	Element root = doc.getRootElement();

	checkRoot(root);
	checkWorkflowBundleDocument(root);

}