org.jdom2.input.SAXBuilder Java Examples

The following examples show how to use org.jdom2.input.SAXBuilder. 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: NcepLocalTables.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Map<Integer, String> initTable410() {
  String path = config.getPath() + "Table4.10.xml";
  try (InputStream is = GribResourceReader.getInputStream(path)) {
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();

    HashMap<Integer, String> result = new HashMap<>(200);
    List<Element> params = root.getChildren("parameter");
    for (Element elem1 : params) {
      int code = Integer.parseInt(elem1.getAttributeValue("code"));
      String desc = elem1.getChildText("description");
      result.put(code, desc);
    }
    return result; // all at once - thread safe

  } catch (IOException | JDOMException ioe) {
    logger.error("Cant read  " + path, ioe);
    return null;
  }
}
 
Example #2
Source File: MCRAclEditorResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected InputStream transform(String xmlFile) throws Exception {
    InputStream guiXML = getClass().getResourceAsStream(xmlFile);
    if (guiXML == null) {
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build());
    }
    SAXBuilder saxBuilder = new SAXBuilder();
    Document webPage = saxBuilder.build(guiXML);
    XPathExpression<Object> xpath = XPathFactory.instance().compile(
        "/MyCoReWebPage/section/div[@id='mycore-acl-editor2']");
    Object node = xpath.evaluateFirst(webPage);
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    String lang = mcrSession.getCurrentLanguage();
    if (node != null) {
        Element mainDiv = (Element) node;
        mainDiv.setAttribute("lang", lang);
        String bsPath = MCRConfiguration2.getString("MCR.bootstrap.path").orElse("");
        if (!"".equals(bsPath)) {
            bsPath = MCRFrontendUtil.getBaseURL() + bsPath;
            Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet")
                .setAttribute("type", "text/css");
            mainDiv.addContent(0, item);
        }
    }
    MCRContent content = MCRJerseyUtil.transform(webPage, request);
    return content.getInputStream();
}
 
Example #3
Source File: XmlMetadataLoader.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends SourceMetadata> T read(String id, InputStream xml) {
    SAXBuilder builder = new SAXBuilder();
    Document doc;
    try {
        doc = builder.build(xml);
    } catch (JDOMException | IOException e) {
        throw new N2oException("Error reading metadata " + id, e);
    }
    Element root = doc.getRootElement();
    T n2o = (T) elementReaderFactory.produce(root).read(root);
    if (n2o == null)
        throw new MetadataReaderException("Xml Element Reader must return not null object");
    n2o.setId(id);
    return n2o;
}
 
Example #4
Source File: XMLBootDelivery.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public XMLBootDelivery(File xmlsource) throws IOException, JDOMException {
	SAXBuilder builder = new SAXBuilder();
	FileInputStream fin = new FileInputStream(xmlsource);
	Document document = builder.build(fin);
	String spaceid = document.getRootElement().getAttribute("SPACE_ID").getValue();
	bootversion = document.getRootElement().getAttribute("VERSION").getValue().replaceAll(spaceid, "").trim();
	if (bootversion.startsWith("_")) bootversion = bootversion.substring(1);
	Iterator<Element> i=document.getRootElement().getChildren().iterator();
	while (i.hasNext()) {
		Element e = i.next();
		XMLBootConfig c = new XMLBootConfig(e.getAttributeValue("NAME"));
		if (e.getChild("BOOT_CONFIG").getChild("FILE") != null) {
			c.setTA(e.getChild("BOOT_CONFIG").getChild("FILE").getAttributeValue("PATH"));
		}
		Iterator<Element> files = e.getChild("BOOT_IMAGES").getChildren().iterator();
		while (files.hasNext()) {
			c.addFile(files.next().getAttributeValue("PATH"));
		}
		c.setAttributes(e.getChild("ATTRIBUTES").getAttributeValue("VALUE"));
		bootconfigs.add(c);
	}
	fin.close();
}
 
Example #5
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 #6
Source File: SvnCommandTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldParseEncodedUrlAndPath() {
    String output = "<?xml version=\"1.0\"?>\n"
            + "<info>\n"
            + "<entry\n"
            + "   kind=\"dir\"\n"
            + "   path=\"unit-reports\"\n"
            + "   revision=\"3\">\n"
            + "<url>file:///C:/Documents%20and%20Settings/cceuser/Local%20Settings/Temp/testSvnRepo-1243722556125/end2end/unit-reports</url>\n"
            + "<repository>\n"
            + "<root>file:///C:/Documents%20and%20Settings/cceuser/Local%20Settings/Temp/testSvnRepo-1243722556125/end2end</root>\n"
            + "<uuid>f953918e-915c-4459-8d4c-83860cce9d9a</uuid>\n"
            + "</repository>\n"
            + "<commit\n"
            + "   revision=\"1\">\n"
            + "<author>cceuser</author>\n"
            + "<date>2008-03-20T04:00:43.976517Z</date>\n"
            + "</commit>\n"
            + "</entry>\n"
            + "</info>";
    SvnCommand.SvnInfo svnInfo = new SvnCommand.SvnInfo();
    svnInfo.parse(output, new SAXBuilder());
    assertThat(svnInfo.getUrl()).isEqualTo("file:///C:/Documents%20and%20Settings/cceuser/Local%20Settings/Temp/testSvnRepo-1243722556125/end2end/unit-reports");
    assertThat(svnInfo.getPath()).isEqualTo("/unit-reports");
}
 
Example #7
Source File: NcmlCollectionReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read an NcML file from a String, and construct a NcmlCollectionReader from its scan or scanFmrc element.
 *
 * @param ncmlString the NcML to construct the reader from
 * @param errlog put error messages here
 * @return the resulting NetcdfDataset
 * @throws IOException on read error, or bad referencedDatasetUri URI
 */
public static NcmlCollectionReader readNcML(String ncmlString, Formatter errlog) throws IOException {
  StringReader reader = new StringReader(ncmlString);

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

  return readXML(doc, errlog, null);
}
 
Example #8
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read NcML doc from an InputStream, and construct a NetcdfDataset.
 *
 * @param ins the InputStream containing the NcML document
 * @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 readNcML(InputStream ins, CancelTask cancelTask) throws IOException {

  org.jdom2.Document doc;
  try {
    SAXBuilder builder = new SAXBuilder();
    doc = builder.build(ins);
  } 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();
  NetcdfDataset ncd = readNcML(null, netcdfElem, cancelTask);
  if (debugOpen)
    System.out.println("***NcMLReader.readNcML (stream) result= \n" + ncd);
  return ncd;
}
 
Example #9
Source File: TestJdom.java    From Java-Data-Science-Cookbook with MIT License 6 votes vote down vote up
public void parseXml(String fileName){
	SAXBuilder builder = new SAXBuilder();
	File file = new File(fileName);
	try {
		Document document = (Document) builder.build(file);
		Element rootNode = document.getRootElement();
		List list = rootNode.getChildren("author");
		for (int i = 0; i < list.size(); i++) {
			Element node = (Element) list.get(i);
			System.out.println("First Name : " + node.getChildText("firstname"));
			System.out.println("Last Name : " + node.getChildText("lastname"));
		}
	} catch (IOException io) {
		System.out.println(io.getMessage());
	} catch (JDOMException jdomex) {
		System.out.println(jdomex.getMessage());
	}



}
 
Example #10
Source File: StationList.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void loadFromXmlFile(String filename) {
  SAXBuilder builder = new SAXBuilder();
  File f = new File(filename);
  try {
    Document doc = builder.build(f);
    Element list = doc.getRootElement();
    for (Element station : list.getChildren()) {
      Element loc = station.getChild("location3D");
      String stid = station.getAttributeValue("value");
      Station newStation = addStation(stid, LatLonPoint.create(Double.valueOf(loc.getAttributeValue("latitude")),
          Double.valueOf(loc.getAttributeValue("longitude"))));
      newStation.setElevation(Double.valueOf(loc.getAttributeValue("elevation")));
      newStation.setName(station.getAttributeValue("name"));
      newStation.setState(station.getAttributeValue("state"));
      newStation.setCountry(station.getAttributeValue("country"));
    }
  } catch (IOException | JDOMException e) {
    e.printStackTrace();
  }
}
 
Example #11
Source File: UscTteCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    inputDir = CORPORA_BASE + "USC_TTE_corpus";
    // inputDir = CORPORA_HOME + "src/test/resources/corpus/USC_TTE_corpus";
    docCnt = 1;
    super.initialize(context);
    try {
        File corpusDir = new File(inputDir);
        checkArgument(corpusDir.exists());
        // duplicating code from AbstractFileReader to add "xml" filtering
        fileIterator = DirectoryIterator.get(directoryIterator, corpusDir,
                "xml", false);
        builder = new SAXBuilder();
        xo = new XMLOutputter();
        xo.setFormat(Format.getRawFormat());
        sentenceXPath = XPathFactory.instance().compile("//S");
    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceInitializationException.NO_RESOURCE_FOR_PARAMETERS,
                new Object[] { inputDir });
    }
}
 
Example #12
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 #13
Source File: SvnLogXmlParserTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseSvnLogContainingNullComments() throws IOException {
    String xml;
    try (InputStream stream = getClass().getResourceAsStream("jemstep_svn_log.xml")) {
        xml = IOUtils.toString(stream, UTF_8);
    }
    SvnLogXmlParser parser = new SvnLogXmlParser();
    List<Modification> revisions = parser.parse(xml, "", new SAXBuilder());

    assertThat(revisions.size(), is(43));

    Modification modWithoutComment = null;
    for (Modification revision : revisions) {
        if (revision.getRevision().equals("7815")) {
            modWithoutComment = revision;
        }
    }

    assertThat(modWithoutComment.getComment(), is(nullValue()));
}
 
Example #14
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 #15
Source File: NcepLocalParams.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean readParameterTableFromResource(String resource) {
  if (debugOpen)
    logger.debug("readParameterTableFromResource from resource {}", resource);
  ClassLoader cl = this.getClass().getClassLoader();
  try (InputStream is = cl.getResourceAsStream(resource)) {
    if (is == null) {
      logger.info("Cant read resource " + resource);
      return false;
    }
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();
    paramMap = parseXml(root); // all at once - thread safe
    return true;

  } catch (IOException | JDOMException ioe) {
    ioe.printStackTrace();
    return false;
  }
}
 
Example #16
Source File: XMLUtil.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
public static List readNodeStore(InputStream in) {
    List<Element> returnElement=new LinkedList<Element>();
    try {
        boolean validate = false;
        SAXBuilder builder = new SAXBuilder(validate);
        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 #17
Source File: MyCoReWebPageProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds a section to the MyCoRe webpage.
 * 
 * @param title the title of the section
 * @param xmlAsString xml string which is added to the section
 * @param lang the language of the section specified by a language key.
 * @return added section
 */
public Element addSection(String title, String xmlAsString, String lang) throws IOException, SAXParseException,
    JDOMException {
    String sb = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<!DOCTYPE MyCoReWebPage PUBLIC \"-//MYCORE//DTD MYCOREWEBPAGE 1.0//DE\" "
        + "\"http://www.mycore.org/mycorewebpage.dtd\">" + "<MyCoReWebPage>" + xmlAsString + "</MyCoReWebPage>";
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setEntityResolver((publicId, systemId) -> {
        String resource = systemId.substring(systemId.lastIndexOf("/"));
        InputStream is = getClass().getResourceAsStream(resource);
        if (is == null) {
            throw new IOException(new FileNotFoundException("Unable to locate resource " + resource));
        }
        return new InputSource(is);
    });
    StringReader reader = new StringReader(sb);
    Document doc = saxBuilder.build(reader);
    return this.addSection(title, doc.getRootElement().cloneContent(), lang);
}
 
Example #18
Source File: CodeTableGen.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static public void passTwo() throws IOException {
  org.jdom2.Document tdoc;
  try {
    SAXBuilder builder = new SAXBuilder();
    tdoc = builder.build(trans1);

    org.jdom2.Document ndoc = new org.jdom2.Document();
    Element nroot = new Element("ndoc");
    ndoc.setRootElement(nroot);

    transform2(tdoc.getRootElement(), nroot);

    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    Writer pw = new FileWriter(trans2);
    fmt.output(ndoc, pw);
    pw = new PrintWriter(System.out);
    fmt.output(ndoc, pw);

  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #19
Source File: CodeTableGen.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static public void passThree() throws IOException {
  org.jdom2.Document tdoc;
  try {
    SAXBuilder builder = new SAXBuilder();
    tdoc = builder.build(trans2);

    /*
     * org.jdom2.Document ndoc = new org.jdom2.Document();
     * Element nroot = new Element("ndoc");
     * ndoc.setRootElement(nroot);
     */

    transform3(tdoc.getRootElement());

    /*
     * XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
     * Writer pw = new FileWriter("C:/docs/bufr/wmo/Code-FlagTables-11-2007.trans2.xml");
     * fmt.output(ndoc, pw);
     * pw = new PrintWriter(System.out);
     * fmt.output(ndoc, pw);
     */

  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #20
Source File: SvnLogXmlParserTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseLogEntryWithoutComment() throws ParseException {
    SvnLogXmlParser parser = new SvnLogXmlParser();
    List<Modification> materialRevisions = parser.parse("<?xml version=\"1.0\"?>\n"
            + "<log>\n"
            + "<logentry\n"
            + "   revision=\"3\">\n"
            + "<author>cceuser</author>\n"
            + "<date>2008-03-11T07:52:41.162075Z</date>\n"
            + "<paths>\n"
            + "<path\n"
            + "   action=\"A\">/trunk/revision3.txt</path>\n"
            + "</paths>\n"
            + "</logentry>\n"
            + "</log>", "", new SAXBuilder());
    assertThat(materialRevisions.size(), is(1));
    Modification mod = materialRevisions.get(0);
    assertThat(mod.getRevision(), is("3"));
    assertThat(mod.getComment(), is(nullValue()));
}
 
Example #21
Source File: MCRClassificationEditorResourceTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void saveClassiWithSub() throws Exception {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/classiEditor_ClassiSub.xml"));
    String json = doc.getRootElement().getText();
    Response response = target("/classifications/save").request().post(Entity.json(json));
    assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
 
Example #22
Source File: Grib1ParamTableReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Map<Integer, Grib1Parameter> readParameterTableXml(XmlTableParser parser) throws IOException {
  try (InputStream is = GribResourceReader.getInputStream(path)) {
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();
    return parser.parseXml(root); // all at once - thread safe

  } catch (JDOMException | IOException e) {
    throw new IOException(e);
  }
}
 
Example #23
Source File: JDomParser.java    From tutorials with MIT License 5 votes vote down vote up
public List<Element> getAllTitles() {
    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(this.getFile());
        Element tutorials = doc.getRootElement();
        List<Element> titles = tutorials.getChildren("tutorial");
        return titles;
    } catch (JDOMException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}
 
Example #24
Source File: MCRXMLParserImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public MCRXMLParserImpl(XMLReaderJDOMFactory factory, boolean silent) {
    this.validate = factory.isValidating();
    builder = new SAXBuilder(factory);
    builder.setFeature(FEATURE_NAMESPACES, true);
    builder.setFeature(FEATURE_SCHEMA_SUPPORT, validate);
    builder.setFeature(FEATURE_FULL_SCHEMA_SUPPORT, false);
    builder.setErrorHandler(new MCRXMLParserErrorHandler(silent));
    builder.setEntityResolver(new AbsoluteToRelativeResolver(MCREntityResolver.instance()));
}
 
Example #25
Source File: GoConfigMigration.java    From gocd with Apache License 2.0 5 votes vote down vote up
private int getCurrentSchemaVersion(String content) {
    try {
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(new ByteArrayInputStream(content.getBytes()));
        Element root = document.getRootElement();

        String currentVersion = root.getAttributeValue(schemaVersion) == null ? "0" : root.getAttributeValue(schemaVersion);
        return Integer.parseInt(currentVersion);
    } catch (Exception e) {
        throw bomb(e);
    }
}
 
Example #26
Source File: TestYMarshalB4.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setUp2() throws YSchemaBuildingException, YSyntaxException, JDOMException, IOException {
//        File specificationFile = new File(YMarshal.class.getResource("MakeRecordings.xml").getFile());
        File specificationFile = new File(YMarshal.class.getResource(tempfileName).getFile());
        List specifications = null;
        specifications = YMarshal.unmarshalSpecifications(
                StringUtil.fileToString(specificationFile.getAbsolutePath()));
        _originalSpec = (YSpecification) specifications.iterator().next();
        String marshalledSpecsString = YMarshal.marshal(specifications, _originalSpec.getSchemaVersion());
        SAXBuilder builder = new SAXBuilder();
        StringReader marshalledSpecsStringReader = new StringReader(marshalledSpecsString);
        Document marshalledSpecsStringDoc = builder.build(marshalledSpecsStringReader);
        XMLOutputter marshalledSpecsStringOutputter = new XMLOutputter(Format.getPrettyFormat());
        marshalledSpecsString = marshalledSpecsStringOutputter.outputString(marshalledSpecsStringDoc);
System.out.println("marshalledSpecsString = " + marshalledSpecsString);
        File derivedSpecFile = new File(
                specificationFile.getParent() + File.separator + tempfileName);
        try {
            FileWriter fw = new FileWriter(derivedSpecFile);
            fw.write(marshalledSpecsString);
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        _copy = (YSpecification) YMarshal.unmarshalSpecifications(
                StringUtil.fileToString(derivedSpecFile.getAbsolutePath())).iterator().next();

        derivedSpecFile.delete();
        _originalXMLString = YMarshal.marshal(_originalSpec);
        _copyXMLString = YMarshal.marshal(_copy);
    }
 
Example #27
Source File: JDOMUtil.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * creates a JDOM document from the input XML string.
 *
 * @param xml an XML document in a String
 * @param filter an XMLFilter to receive callbacks during processing
 * @param validate if true, XML should be validated
 * @return the JDOM representation of that XML document
 */
public static Document createDocument(final String xml, final XMLFilter filter, final boolean validate) throws JDOMException {
    final SAXBuilder builder = createSAXBuilder(validate);
    if (filter != null) {
        builder.setXMLFilter(filter);
    }

    try {
        return builder.build(new StringReader(xml));
    } catch (IOException iox) {
        throw new JDOMException("Could not parse document: " + iox.getMessage(), iox);
    }
}
 
Example #28
Source File: NcepLocalParams.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean readParameterTableXml(String path) {
  if (debugOpen)
    logger.debug("readParameterTableXml table {}", path);
  try (InputStream is = GribResourceReader.getInputStream(path)) {
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();
    paramMap = parseXml(root); // all at once - thread safe
    return true;

  } catch (IOException | JDOMException ioe) {
    ioe.printStackTrace();
    return false;
  }
}
 
Example #29
Source File: JDOMUtil.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * creates a JDOM document from the InputSource
 *
 * @param is an XML document in an InputSource
 * @param filter an XMLFilter to receive callbacks during processing
 * @param validate if true, XML should be validated
 * @return the JDOM representation of that XML document
 */
public static Document createDocument(final InputSource is, final XMLFilter filter, final boolean validate) throws JDOMException {
    final SAXBuilder builder = createSAXBuilder(validate);
    if (filter != null) {
        builder.setXMLFilter(filter);
    }

    try {
        return builder.build(is);
    } catch (IOException iox) {
        throw new JDOMException("Could not parse document: " + iox.getMessage(), iox);
    }
}
 
Example #30
Source File: FnmocTables.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private HashMap<Integer, VertCoordType> readFnmocTable3(String path) {
  try (InputStream is = GribResourceReader.getInputStream(path)) {
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();

    HashMap<Integer, VertCoordType> result = new HashMap<>(200);
    Element fnmocTable = root.getChild("fnmocTable");
    List<Element> params = fnmocTable.getChildren("entry");
    for (Element elem1 : params) {
      int code = Integer.parseInt(elem1.getChildText("grib1Id"));
      if (code < 129)
        continue;
      String desc = elem1.getChildText("description");
      String abbrev = elem1.getChildText("name");
      String units = elem1.getChildText("units");
      if (units == null)
        units = (code == 219) ? "Pa" : "";
      String datum = elem1.getChildText("datum");
      boolean isLayer = elem1.getChild("isLayer") != null;
      boolean isPositiveUp = elem1.getChild("isPositiveUp") != null;
      VertCoordType lt = new VertCoordType(code, desc, abbrev, units, datum, isPositiveUp, isLayer);
      result.put(code, lt);
    }

    return result; // all at once - thread safe

  } catch (IOException | JDOMException e) {
    logger.error("Cant read FnmocTable3 = " + path, e);
    return null;
  }
}