org.jdom2.output.Format Java Examples

The following examples show how to use org.jdom2.output.Format. 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 Project: netcdf-java   Author: Unidata   File: GridDatasetInfo.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Element writeBoundingBox(LatLonRect bb) {

    Element bbElem = new Element("LatLonBox");
    // LatLonPoint llpt = bb.getLowerLeftPoint();
    // LatLonPoint urpt = bb.getUpperRightPoint();

    // bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(llpt.getLongitude(), 4)));
    bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMin(), 4)));
    // bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(urpt.getLongitude(), 4)));
    bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMax(), 4)));
    // bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(llpt.getLatitude(), 4)));
    bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMin(), 4)));
    // bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(urpt.getLatitude(), 4)));
    bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMax(), 4)));

    return bbElem;

  }
 
Example #2
private Element writeBoundingBox(LatLonRect bb) {
  int decToKeep = 6;
  double bbExpand = Math.pow(10, -decToKeep);

  // extend the bbox to make sure the implicit rounding does not result in a bbox that does not contain
  // any points (can happen when you have a single station with very precise lat/lon values)
  // See https://github.com/Unidata/thredds/issues/470
  // This accounts for the implicit rounding errors that result from the use of
  // ucar.unidata.util.Format.dfrac when writing out the lat/lon box on the NCSS for Points dataset.html
  // page
  LatLonPoint extendNorthEast = LatLonPoint.create(bb.getLatMax() + bbExpand, bb.getLonMax() + bbExpand);
  LatLonPoint extendSouthWest = LatLonPoint.create(bb.getLatMin() - bbExpand, bb.getLonMin() - bbExpand);
  bb.extend(extendNorthEast);
  bb.extend(extendSouthWest);

  Element bbElem = new Element("LatLonBox"); // from KML

  bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMin(), decToKeep)));
  bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMax(), decToKeep)));
  bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMin(), decToKeep)));
  bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMax(), decToKeep)));
  return bbElem;
}
 
Example #3
private Element writeBoundingBox(LatLonRect bb) {
  int decToKeep = 6;
  double bbExpand = Math.pow(10, -decToKeep);

  // extend the bbox to make sure the implicit rounding does not result in a bbox that does not contain
  // any points (can happen when you have a single station with very precise lat/lon values)
  // See https://github.com/Unidata/thredds/issues/470
  // This accounts for the implicit rounding errors that result from the use of
  // ucar.unidata.util.Format.dfrac when writing out the lat/lon box on the NCSS for Points dataset.html
  // page
  LatLonPoint extendNorthEast = LatLonPoint.create(bb.getLatMax() + bbExpand, bb.getLonMax() + bbExpand);
  LatLonPoint extendSouthWest = LatLonPoint.create(bb.getLatMin() - bbExpand, bb.getLonMin() - bbExpand);
  bb.extend(extendNorthEast);
  bb.extend(extendSouthWest);

  Element bbElem = new Element("LatLonBox"); // from KML

  bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMin(), decToKeep)));
  bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMax(), decToKeep)));
  bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMin(), decToKeep)));
  bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMax(), decToKeep)));
  return bbElem;
}
 
Example #4
Source Project: mycore   Author: MyCoRe-Org   File: MCRMetaISO8601DateTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void createXML() {
    MCRMetaISO8601Date ts = new MCRMetaISO8601Date("servdate", "createdate", 0);
    String timeString = "1997-07-16T19:20:30.452300+01:00";
    ts.setDate(timeString);
    assertNotNull("Date is null", ts.getDate());
    Element export = ts.createXML();
    if (LOGGER.isDebugEnabled()) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        StringWriter sw = new StringWriter();
        try {
            xout.output(export, sw);
            LOGGER.debug(sw.toString());
        } catch (IOException e) {
            LOGGER.warn("Failure printing xml result", e);
        }
    }
}
 
Example #5
Source Project: web-data-extractor   Author: fivesmallq   File: XPathExtractor.java    License: Apache License 2.0 6 votes vote down vote up
private String wrap(Object text) {
    if (text != null) {
        if (text instanceof Attribute) {
            return StringEscapeUtils.unescapeHtml4(((Attribute) text).getValue());
        } else if (text instanceof Content) {
            XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
            if (text instanceof Element) {
                return StringEscapeUtils.unescapeHtml4(xout.outputString((Element) text));
            }
            if (text instanceof Text) {
                return StringEscapeUtils.unescapeHtml4(xout.outputString((Text) text));
            }
        } else {
            LOGGER.error("unsupported document type", text.getClass());
        }
    }
    return "";
}
 
Example #6
Source Project: netcdf-java   Author: Unidata   File: NcepHtmlScraper.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeTable2Xml(String name, String source, String filename, List<Param> params) throws IOException {
  org.jdom2.Element rootElem = new org.jdom2.Element("parameterMap");
  org.jdom2.Document doc = new org.jdom2.Document(rootElem);
  rootElem.addContent(new org.jdom2.Element("title").setText(name));
  rootElem.addContent(new org.jdom2.Element("source").setText(source));

  for (Param p : params) {
    org.jdom2.Element paramElem = new org.jdom2.Element("parameter");
    paramElem.setAttribute("code", Integer.toString(p.pnum));
    paramElem.addContent(new org.jdom2.Element("shortName").setText(p.name));
    paramElem.addContent(new org.jdom2.Element("description").setText(p.desc));
    paramElem.addContent(new org.jdom2.Element("units").setText(p.unit));
    rootElem.addContent(paramElem);
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  String x = fmt.outputString(doc);

  try (FileOutputStream fout = new FileOutputStream(dirOut + filename)) {
    fout.write(x.getBytes(StandardCharsets.UTF_8));
  }

  if (show)
    System.out.printf("%s%n", x);
}
 
Example #7
Source Project: weasis-pacs-connector   Author: nroduit   File: JnlpLauncher.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected String buildJnlpResponse(JnlpTemplate launcher) throws ServletErrorException {

        launcher.rootElt.setAttribute(JNLP_TAG_ATT_CODEBASE,
            ServletUtil.getFirstParameter(launcher.parameterMap.get(WeasisConfig.PARAM_CODEBASE)));
        launcher.rootElt.removeAttribute(JNLP_TAG_ATT_HREF); // this tag has not to be used inside dynamic JNLP

        handleRequestPropertyParameter(launcher);
        handleRequestArgumentParameter(launcher);

        filterRequestParameterMarker(launcher);

        String outputStr = null;
        try {
            Format format = Format.getPrettyFormat();
            // Converts native encodings to ASCII with escaped Unicode like (ô è é...),
            // necessary for jnlp
            format.setEncoding("US-ASCII");
            outputStr = new XMLOutputter(format).outputString(launcher.rootElt);
        } catch (Exception e) {
            throw new ServletErrorException(HttpServletResponse.SC_NOT_MODIFIED, "Can't build Jnlp launcher ", e);
        }

        return outputStr;
    }
 
Example #8
Source Project: tds   Author: Unidata   File: XsltForHtmlView.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void renderMergedOutputModel(Map model, HttpServletRequest req, HttpServletResponse res) throws Exception {
  res.setContentType(getContentType());

  Document doc = (Document) model.get("Document");
  String transform = (String) model.get("Transform");
  String resourceName = "/resources/xsl/" + transform;
  Resource resource = new ClassPathResource(resourceName);
  try (InputStream is = resource.getInputStream()) {
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(is));
    transformer.setParameter("tdsContext", req.getContextPath());

    JDOMSource in = new JDOMSource(doc);
    JDOMResult out = new JDOMResult();
    transformer.transform(in, out);
    Document html = out.getDocument();
    if (html == null)
      throw new IllegalStateException("Bad XSLT=" + resourceName);

    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    fmt.output(html, res.getOutputStream());
  }
}
 
Example #9
Source Project: tds   Author: Unidata   File: MetadataController.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String writeXML(ThreddsMetadata.VariableGroup vars) {
  Document doc = new Document();
  Element elem = new Element("variables", Catalog.defNS);
  doc.setRootElement(elem);

  if (vars.getVocabulary() != null)
    elem.setAttribute("vocabulary", vars.getVocabulary());
  if (vars.getVocabUri() != null)
    elem.setAttribute("href", vars.getVocabUri().href, Catalog.xlinkNS);

  List<ThreddsMetadata.Variable> varList = vars.getVariableList();
  for (ThreddsMetadata.Variable v : varList) {
    elem.addContent(writeVariable(v));
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  return fmt.outputString(doc);
}
 
Example #10
Source Project: mycore   Author: MyCoRe-Org   File: MCRXMLMetadataManagerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void retrieve() throws JDOMException, IOException, SAXException {
    assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(),
        SAX_BUILDER.build(new ByteArrayInputStream(MyCoRe_document_00000001.blob)).getRootElement()
            .getAttributeValue("id"));
    getStore().create(MyCoRe_document_00000001.id,
        new MCRByteContent(MyCoRe_document_00000001.blob, MCR_document_00000001.lastModified.getTime()),
        MyCoRe_document_00000001.lastModified);
    MCRVersionedMetadata data = getStore().getVersionedMetaData(MyCoRe_document_00000001.id);
    assertFalse(data.isDeleted());
    assertFalse(data.isDeletedInRepository());
    Document doc = getStore().retrieveXML(MyCoRe_document_00000001.id);
    assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(), doc.getRootElement()
        .getAttributeValue("id"));
    try {
        doc = getStore().retrieveXML(MCR_document_00000001.id);
        if (doc != null) {
            fail("Requested " + MCR_document_00000001.id + ", retrieved wrong document:\n"
                + new XMLOutputter(Format.getPrettyFormat()).outputString(doc));
        }
    } catch (Exception e) {
        //this is ok
    }
}
 
Example #11
Source Project: gama   Author: gama-platform   File: UnifyDoc.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void unify(boolean local) {
	try {

		WorkspaceManager ws = new WorkspaceManager(".",local);
		HashMap<String, File> hmFiles = ws.getProductDocFiles();

		Document doc = mergeFiles(hmFiles);

		System.out.println("" + hmFiles);

		XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		sortie.output(doc, new FileOutputStream(Constants.DOCGAMA_GLOBAL_FILE));
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example #12
Source Project: mule-intellij-plugins   Author: machaval   File: SOAPKitScaffoldingAction.java    License: Apache License 2.0 6 votes vote down vote up
private void writeMuleXmlFile(Element element, VirtualFile muleConfig) {

        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        InputStream inputStream = null;
        try {
            String outputString = xout.outputString(element);
            logger.debug("*** OUTPUT STRING IS " + outputString);
            OutputStreamWriter writer = new OutputStreamWriter(muleConfig.getOutputStream(this));
            writer.write(outputString);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            logger.error("Unable to write file: " + e);
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
 
Example #13
Source Project: mycore   Author: MyCoRe-Org   File: MCROAIDataProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    // get base url
    if (this.myBaseURL == null) {
        this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1);
    }
    logRequest(request);
    // create new oai request
    OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap()));
    // create new oai provider
    OAIProvider oaiProvider = oaiAdapterServiceLoader
        .findFirst()
        .orElseThrow(() -> new ServletException("No implementation of " + OAIProvider.class + " found."));
    oaiProvider.setAdapter(getOAIAdapter());
    // handle request
    OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest);
    // build response
    Element xmlRespone = oaiResponse.toXML();
    // fire
    job.getResponse().setContentType("text/xml; charset=UTF-8");
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat(), OAI_XML_OUTPUT_PROCESSOR);
    xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream());
}
 
Example #14
Source Project: mycore   Author: MyCoRe-Org   File: MCRMODSLinkedMetadataTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testUpdate() throws IOException, URISyntaxException, MCRPersistenceException,
    MCRActiveLinkException, JDOMException, SAXException, MCRAccessException {
    MCRObject seriesNew = new MCRObject(getResourceAsURL(seriesID + "-updated.xml").toURI());
    MCRMetadataManager.update(seriesNew);
    Document bookNew = MCRXMLMetadataManager.instance().retrieveXML(bookID);
    XPathBuilder<Element> builder = new XPathBuilder<>(
        "/mycoreobject/metadata/def.modsContainer/modsContainer/mods:mods/mods:relatedItem/mods:titleInfo/mods:title",
        Filters.element());
    builder.setNamespace(MCRConstants.MODS_NAMESPACE);
    XPathExpression<Element> seriesTitlePath = builder.compileWith(XPathFactory.instance());
    Element titleElement = seriesTitlePath.evaluateFirst(bookNew);
    Assert.assertNotNull(
        "No title element in related item: " + new XMLOutputter(Format.getPrettyFormat()).outputString(bookNew),
        titleElement);
    Assert.assertEquals("Title update from series was not promoted to book of series.",
        "Updated series title", titleElement.getText());
}
 
Example #15
Source Project: orcas   Author: opitzconsulting   File: XmlLogFileHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void writeXmlFile( String pXmlLogFile, Document pDocument )
{
  try
  {
    File lXmlLogFile = new File( pXmlLogFile );

    if( !lXmlLogFile.getParentFile().exists() )
    {
      lXmlLogFile.getParentFile().mkdirs();
    }

    Format lFormat = Format.getPrettyFormat();
    lFormat.setEncoding( _parameters.getEncodingForSqlLog().name() );
    new XMLOutputter( lFormat ).output( pDocument, new FileOutputStream( lXmlLogFile ) );
  }
  catch( Exception e )
  {
    throw new RuntimeException( e );
  }
}
 
Example #16
Source Project: mycore   Author: MyCoRe-Org   File: MCRWCMSUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts the navigation.xml to the old format.
 */
private static byte[] convertToOldFormat(byte[] xml) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new ByteArrayInputStream(xml));
    Element rootElement = doc.getRootElement();
    rootElement.setAttribute("href", rootElement.getName());
    List<Element> children = rootElement.getChildren();
    for (Element menu : children) {
        String id = menu.getAttributeValue("id");
        menu.setName(id);
        menu.setAttribute("href", id);
        menu.removeAttribute("id");
    }
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    ByteArrayOutputStream bout = new ByteArrayOutputStream(xml.length);
    out.output(doc, bout);
    return bout.toByteArray();
}
 
Example #17
Source Project: mycore   Author: MyCoRe-Org   File: ItemTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.item, JDOMResult);
    Element itemElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(itemElement, System.out);

    assertEquals("template_mysample", itemElement.getAttributeValue("template"));
    assertEquals("bold", itemElement.getAttributeValue("style"));
    assertEquals("_self", itemElement.getAttributeValue("target"));
    assertEquals("intern", itemElement.getAttributeValue("type"));
    assertEquals("true", itemElement.getAttributeValue("constrainPopUp"));
    assertEquals("false", itemElement.getAttributeValue("replaceMenu"));
    assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey"));

    Element label1 = itemElement.getChildren().get(0);
    Element label2 = itemElement.getChildren().get(1);

    assertEquals("Deutschland", label1.getValue());
    assertEquals("England", label2.getValue());
}
 
Example #18
Source Project: mycore   Author: MyCoRe-Org   File: NavigationTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.navigation, JDOMResult);
    Element navigationElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(navigationElement, System.out);

    // test attributes
    assertEquals("template_mysample", navigationElement.getAttributeValue("template"));
    assertEquals("/content", navigationElement.getAttributeValue("dir"));
    assertEquals("History Title", navigationElement.getAttributeValue("historyTitle"));
    assertEquals("/content/below/index.xml", navigationElement.getAttributeValue("hrefStartingPage"));
    assertEquals("Main Title", navigationElement.getAttributeValue("mainTitle"));
    // test children
    assertEquals(2, navigationElement.getChildren("menu").size());
    assertEquals(1, navigationElement.getChildren("insert").size());
}
 
Example #19
Source Project: mycore   Author: MyCoRe-Org   File: MCRCategoryDAOImplTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@After
@Override
public void tearDown() throws Exception {
    try {
        startNewTransaction();
        MCRCategoryImpl rootNode = getRootCategoryFromSession();
        MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1);
        if (rootNode != null) {
            try {
                checkLeftRightLevelValue(rootNode, 0, 0);
                checkLeftRightLevelValue(rootNode2, 0, 0);
            } catch (AssertionError e) {
                LogManager.getLogger().error("Error while checking left, right an level values in database.");
                new XMLOutputter(Format.getPrettyFormat())
                    .output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out);
                printCategoryTable();
                throw e;
            }
        }
    } finally {
        super.tearDown();
    }
}
 
Example #20
Source Project: CardinalPGM   Author: twizmwazin   File: Database.java    License: MIT License 6 votes vote down vote up
public boolean save(File file) {
    XMLOutputter out = new XMLOutputter();
    out.setFormat(Format.getPrettyFormat());
    try {
        if (file.createNewFile()) {
            Cardinal.getInstance().getLogger().info("Database file not found, creating...");
            out.output(document, new FileWriter(file));
            return true;
        } else {
            out.output(document, new FileWriter(file));
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #21
Source Project: mycore   Author: MyCoRe-Org   File: MCRUserManagerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public final void toXML() throws IOException {
    MCRUserManager.updatePasswordHashToSHA256(this.user, this.user.getPassword());
    this.user.setEMail("[email protected]");
    this.user.setHint("JUnit Test");
    this.user.getSystemRoleIDs().add("admin");
    this.user.getSystemRoleIDs().add("editor");
    this.user.setLastLogin(new Date());
    this.user.setRealName("Test Case");
    this.user.setUserAttribute("tel", "555 4812");
    this.user.setUserAttribute("street", "Heidestraße 12");
    this.user.getAttributes().add(new MCRUserAttribute("tel", "555 4711"));
    this.user.setOwner(this.user);
    MCRUserManager.updateUser(this.user);
    startNewTransaction();
    assertEquals("Too many users", 1, MCRUserManager.countUsers(null, null, null));
    assertEquals("Too many users", 1, MCRUserManager.listUsers(this.user).size());
    Document exportableXML = MCRUserTransformer.buildExportableXML(this.user);
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(exportableXML, System.out);
}
 
Example #22
Source Project: mycore   Author: MyCoRe-Org   File: MCRMetaDefaultListXMLWriter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(List<? extends MCRMetaDefault> mcrMetaDefaults, Class<?> type, Type genericType,
    Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
    OutputStream entityStream) throws IOException, WebApplicationException {
    Optional<String> wrapper = getWrapper(annotations);
    if (!wrapper.isPresent()) {
        throw new InternalServerErrorException("Could not get XML wrapping element from annotations.");
    }
    httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE);
    Element root = new Element(wrapper.get());
    root.addContent(mcrMetaDefaults.stream()
        .map(MCRMetaDefault::createXML)
        .collect(Collectors.toList()));
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(root, entityStream);
}
 
Example #23
Source Project: netcdf-java   Author: Unidata   File: ThreddsMetadata.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void toXML(java.io.OutputStream out) throws IOException {
  // hack, hack
  InvCatalogFactory10 converter = new InvCatalogFactory10();
  Element elem = converter.writeGeospatialCoverage(this);
  // XMLOutputter outputter = new XMLOutputter(" ", true);
  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  fmt.output(elem, out);
}
 
Example #24
Source Project: yawl   Author: yawlfoundation   File: JDOMUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/****************************************************************************/

    public static String elementToStringDump(Element e) {
        if (e == null) return null ;
        XMLOutputter out = new XMLOutputter(Format.getCompactFormat());
        return out.outputString(e);
    }
 
Example #25
Source Project: mycore   Author: MyCoRe-Org   File: MCRMetaNumberTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void print_data(Element imported, Element exported) {
    if (LOGGER.isDebugEnabled()) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        StringWriter sw = new StringWriter();
        StringWriter sw2 = new StringWriter();
        try {
            xout.output(imported, sw);
            LOGGER.info(sw.toString());
            xout.output(exported, sw2);
            LOGGER.info(sw2.toString());
        } catch (IOException e) {
            LOGGER.warn("Failure printing xml result", e);
        }
    }
}
 
Example #26
Source Project: netcdf-java   Author: Unidata   File: StationObsDatasetInfo.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Element writeBoundingBox(LatLonRect bb) {
  Element bbElem = new Element("LatLonBox");
  bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMin(), 4)));
  bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMax(), 4)));
  bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMin(), 4)));
  bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMax(), 4)));
  return bbElem;
}
 
Example #27
Source Project: yawl   Author: yawlfoundation   File: YNet.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setIncomingData(YPersistenceManager pmgr, Element incomingData)
        throws YDataStateException, YPersistenceException {
    for (YParameter parameter : getInputParameters().values()) {
        Element actualParam = incomingData.getChild(parameter.getName());
        if (parameter.isMandatory() && actualParam == null) {
            throw new IllegalArgumentException("The input data for Net:" + getID() +
                    " is missing mandatory input data for a parameter (" + parameter.getName() + ").  " +
                    " Alternatively the data is there but the query in the super net produced data with" +
                    " the wrong name (Check your specification). "
                    + new XMLOutputter(Format.getPrettyFormat()).outputString(incomingData).trim());
        }

        // remove any attributes - not required and cause validation errors if left
        if ((actualParam != null) && ! actualParam.getAttributes().isEmpty()) {
            JDOMUtil.stripAttributes(actualParam);
        }
    }

    // validate against schema
    getSpecification().getDataValidator().validate(
                               getInputParameters().values(), incomingData, getID());

    for (Element element : incomingData.getChildren()) {
        if (getInputParameters().containsKey(element.getName())) {
            addData(pmgr, element.clone());
        }
        else {
            throw new IllegalArgumentException("Element " + element +
                    " is not a valid input parameter of " + this);
        }
    }
}
 
Example #28
Source Project: iaf   Author: ibissource   File: IbisXmlLayout.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
	Document document = new Document(element.detach());
	XMLOutputter xmlOutputter = new XMLOutputter();
	xmlOutputter.setFormat(Format.getPrettyFormat().setOmitDeclaration(true));
	return xmlOutputter.outputString(document);
}
 
Example #29
Source Project: mycore   Author: MyCoRe-Org   File: MCREditorOutValidator.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * instantiate the validator with the editor input <code>jdom_in</code>.
 * 
 * <code>id</code> will be set as the MCRObjectID for the resulting object
 * that can be fetched with <code>generateValidMyCoReObject()</code>
 * 
 * @param jdomIn
 *            editor input
 */
public MCREditorOutValidator(Document jdomIn, MCRObjectID id) throws JDOMException, IOException {
    errorlog = new ArrayList<>();
    input = jdomIn;
    this.id = id;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("XML before validation:\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(input));
    }
    checkObject();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("XML after validation:\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(input));
    }
}
 
Example #30
Source Project: dsworkbench   Author: Torridity   File: JDomUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void saveDocument(Document pDoc, String filename) {
    try {
        XMLOutputter xmlOutput = new XMLOutputter();
        
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(pDoc, new FileWriter(filename));
    } catch (Exception e) {
        logger.warn("Unable to save document", e);
    }
}