Java Code Examples for org.jdom2.output.XMLOutputter#output()

The following examples show how to use org.jdom2.output.XMLOutputter#output() . 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: MetsResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/crud/{derivateId}")
public String save(@PathParam("derivateId") String derivateId, String data) {
    MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId);

    checkDerivateExists(derivateIdObject);
    checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_WRITE);

    MCRMetsSimpleModel model = MCRJSONSimpleModelConverter.toSimpleModel(data);
    Document document = MCRSimpleModelXMLConverter.toXML(model);
    XMLOutputter o = new XMLOutputter();
    try (OutputStream out = Files.newOutputStream(MCRPath.getPath(derivateId, METS_XML_PATH),
        StandardOpenOption.CREATE,
        StandardOpenOption.TRUNCATE_EXISTING)) {
        o.output(document, out);
    } catch (IOException e) {
        throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
    }

    return "{ \"success\": true }";
}
 
Example 2
Source File: MCRMetaISO8601DateTest.java    From mycore with 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 3
Source File: UnifyDoc.java    From gama with 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 4
Source File: MCRWCMSDefaultSectionProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the content of an element as string. The element itself
 * is ignored.
 * 
 * @param e the element to get the content from
 * @return the content as string
 */
protected String getContent(Element e) throws IOException {
    XMLOutputter out = new XMLOutputter();
    StringWriter writer = new StringWriter();
    for (Content child : e.getContent()) {
        if (child instanceof Element) {
            out.output((Element) child, writer);
        } else if (child instanceof Text) {
            Text t = (Text) child;
            String trimmedText = t.getTextTrim();
            if (!"".equals(trimmedText)) {
                Text newText = new Text(trimmedText);
                out.output(newText, writer);
            }
        }
    }
    return writer.toString();
}
 
Example 5
Source File: MCRMetaDefaultListXMLWriter.java    From mycore with 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 6
Source File: MCRWebsiteWriteProtection.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static void setConfiguration(Element configXML) {
    try {
        // save
        XMLOutputter xmlOut = new XMLOutputter();
        FileOutputStream fos = new FileOutputStream(CONFIG_FILE);
        xmlOut.output(configXML, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    updateCache(configXML);
}
 
Example 7
Source File: MCRAccessCommands.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method just export the permissions to a file
 * 
 * @param filename
 *            the file written to
 */
@MCRCommand(syntax = "export all permissions to file {0}",
    help = "Export all permissions from the Access Control System to the file {0}.",
    order = 50)
public static void exportAllPermissionsToFile(String filename) throws Exception {
    MCRAccessInterface accessImpl = MCRAccessManager.getAccessImpl();

    Element mcrpermissions = new Element("mcrpermissions");
    mcrpermissions.addNamespaceDeclaration(XSI_NAMESPACE);
    mcrpermissions.addNamespaceDeclaration(XLINK_NAMESPACE);
    mcrpermissions.setAttribute("noNamespaceSchemaLocation", "MCRPermissions.xsd", XSI_NAMESPACE);
    Document doc = new Document(mcrpermissions);
    Collection<String> permissions = accessImpl.getPermissions();
    for (String permission : permissions) {
        Element mcrpermission = new Element("mcrpermission");
        mcrpermission.setAttribute("name", permission);
        String ruleDescription = accessImpl.getRuleDescription(permission);
        if (!ruleDescription.equals("")) {
            mcrpermission.setAttribute("ruledescription", ruleDescription);
        }
        Element rule = accessImpl.getRule(permission);
        mcrpermission.addContent(rule);
        mcrpermissions.addContent(mcrpermission);
    }
    File file = new File(filename);
    if (file.exists()) {
        LOGGER.warn("File {} yet exists, overwrite.", filename);
    }
    FileOutputStream fos = new FileOutputStream(file);
    LOGGER.info("Writing to file {} ...", filename);
    String mcrEncoding = MCRConfiguration2.getString("MCR.Metadata.DefaultEncoding").orElse(DEFAULT_ENCODING);
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setEncoding(mcrEncoding));
    out.output(doc, fos);
}
 
Example 8
Source File: JDOMUtil.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** saves a JDOM Document to a file */
public static void documentToFile(Document doc, String path)   {
    try {
        FileOutputStream fos = new FileOutputStream(path);
        XMLOutputter xop = new XMLOutputter(Format.getPrettyFormat());
        xop.output(doc, fos);
        fos.flush();
        fos.close();
    }
    catch (IOException ioe){
        _log.error("IO Exception in saving Document to file, filepath = " + path, ioe) ;
    }
}
 
Example 9
Source File: MetadataPersister.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends N2oMetadata> void persist(T n2o, String directory) {
    boolean isCreate = metadataRegister.contains(n2o.getId(), n2o.getClass());
    checkLock();
    Element element = persisterFactory.produce(n2o).persist(n2o, n2o.getNamespace());
    Document doc = new Document();
    doc.addContent(element);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(XmlUtil.N2O_FORMAT);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        xmlOutput.output(doc, outputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    InfoConstructor info = findOrCreateXmlInfo(n2o, directory);
    String path = PathUtil.convertUrlToAbsolutePath(info.getURI());
    if (path == null)
        throw new IllegalStateException();
    watchDir.skipOn(path);
    try {
        saveContentToFile(new ByteArrayInputStream(outputStream.toByteArray()), new File(path));
        metadataRegister.update(info);//if exists
        metadataRegister.add(info);
        eventBus.publish(new ConfigPersistEvent(this, info, isCreate));
    } finally {
        watchDir.takeOn(path);
    }
}
 
Example 10
Source File: ODLparser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void showDoc(PrintWriter out) {
  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  try {
    fmt.output(doc, out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 11
Source File: XmlCustomModifier.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() throws Exception {
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    try (FileWriter fileWriter = new FileWriter(xmlFile)) {
        xmlOutput.output(document, fileWriter);
    }
}
 
Example 12
Source File: GPXFileWriter.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void writeGeonames(List<Geonames.Geoname> names, File target, Context context) throws IOException {
    Document doc = new Document();
    Element gpx = new Element("gpx", NS);
    Namespace xsi = Namespace.getNamespace("xsi", XSI);
    gpx.addNamespaceDeclaration(xsi);
    Namespace bpt2 = Namespace.getNamespace("bpt2", BPT);
    gpx.addNamespaceDeclaration(bpt2);
    gpx.setAttribute("schemaLocation", XSD, xsi);
    gpx.setAttribute(new Attribute("version", "1.1"));
    gpx.setAttribute(new Attribute("creator", CREATOR));

    Collection<Element> wpts = new ArrayList<>();
    for (Geonames.Geoname name : names) {
        Element wpt = new Element("wpt", NS);
        wpt.setAttribute(new Attribute("lat", Double.toString(name.location.getLatitude())));
        wpt.setAttribute(new Attribute("lon", Double.toString(name.location.getLongitude())));
        wpt.addContent(new Element("name", NS).addContent(name.name));
        wpts.add(wpt);
    }
    gpx.addContent(wpts);

    doc.setRootElement(gpx);

    FileWriter fw = null;
    try {
        fw = new FileWriter(target);
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        xout.output(doc, fw);
        fw.flush();
    } finally {
        if (fw != null)
            fw.close();
    }
}
 
Example 13
Source File: MCRWCMSUtil.java    From mycore with GNU General Public License v3.0 5 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 14
Source File: ConsistentDatesTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@Ignore("WMS not working")
public void checkWMSDates() throws JDOMException, IOException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "/wms/cdmUnitTest/ncss/climatology/PF5_SST_Climatology_Monthly_1985_2001.nc?service=WMS&version=1.3.0&request=GetCapabilities");
  byte[] result = TestOnLocalServer.getContent(endpoint, 200, ContentType.xml);
  Reader in = new StringReader(new String(result, StandardCharsets.UTF_8));
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build(in);

  if (show) {
    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    fmt.output(doc, System.out);
  }

  XPath xPath = XPath.newInstance("//wms:Dimension");
  xPath.addNamespace("wms", doc.getRootElement().getNamespaceURI());
  Element dimNode = (Element) xPath.selectSingleNode(doc);
  // List<String> content = Arrays.asList(dimNode.getText().trim().split(","));
  List<String> content = new ArrayList<>();
  for (String d : Arrays.asList(dimNode.getText().trim().split(","))) {
    // System.out.printf("Date= %s%n", d);
    CalendarDate cd = CalendarDate.parseISOformat(null, d);
    content.add(cd.toString());
  }

  assertEquals(expectedDatesAsDateTime, content);
}
 
Example 15
Source File: NetcdfDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void writeXML(OutputStream os) throws IOException {
  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  fmt.output(makeDocument(), os);
}
 
Example 16
Source File: KMLFileWriter.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void writeKMLFile(File target, String trackName, boolean extensions, Cursor cTrackPoints, Cursor cWayPoints, Context context)
        throws IOException {

    // https://developers.google.com/kml/documentation/kmlreference
    Document doc = new Document();

    Element kml = new Element("kml", NS);
    Namespace gx = Namespace.getNamespace("gx", "http://www.google.com/kml/ext/2.2");
    kml.addNamespaceDeclaration(gx);
    Namespace atom = Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom");
    kml.addNamespaceDeclaration(atom);

    Element document = new Element("Document", NS);

    Element name = new Element("name", NS);
    name.addContent(trackName);
    document.addContent(name);

    Element author = new Element("author", atom);
    Element authorName = new Element("name", atom);
    authorName.addContent("BackPackTrackII");
    author.addContent(authorName);
    document.addContent(author);

    Element style = new Element("Style", NS);
    style.setAttribute(new Attribute("id", "style"));
    Element linestyle = new Element("LineStyle", NS);
    Element color = new Element("color", NS);
    color.addContent("ffff0000");
    linestyle.addContent(color);
    Element width = new Element("width", NS);
    width.addContent("5");
    linestyle.addContent(width);
    style.addContent(linestyle);
    document.addContent(style);

    Collection<Element> placemarks = new ArrayList<>();
    placemarks.add(getTrackpoints(trackName, extensions, cTrackPoints, gx, context));
    placemarks.addAll(getWayPoints(extensions, cWayPoints, gx, context));
    document.addContent(placemarks);
    kml.addContent(document);
    doc.setRootElement(kml);

    FileWriter fw = null;
    try {
        fw = new FileWriter(target);
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        xout.output(doc, fw);
        fw.flush();
    } finally {
        if (fw != null)
            fw.close();
    }

    // https://developers.google.com/kml/schema/kml22gx.xsd
    // xmllint --noout --schema kml22gx.xsd BackPackTrack.kml
}
 
Example 17
Source File: GetCapabilities.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void writeCapabilitiesReport(PrintWriter pw) throws WcsException, IOException {
  XMLOutputter xmlOutputter = new XMLOutputter(org.jdom2.output.Format.getPrettyFormat());
  xmlOutputter.output(getCapabilitiesReport(), pw);
}
 
Example 18
Source File: StationObsDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void writeStationCollectionXML(OutputStream os) throws IOException {
  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  fmt.output(makeStationCollectionDocument(), os);
}
 
Example 19
Source File: WireFeedOutput.java    From rome with Apache License 2.0 4 votes vote down vote up
/**
 * Writes to an Writer the XML representation for the given WireFeed.
 * <p>
 * If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
 * the responsibility of the developer to ensure the Writer instance is using the same charset
 * encoding.
 * <p>
 * NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'.
 * <p>
 *
 * @param feed Abstract feed to create XML representation from. The type of the WireFeed must
 *            match the type given to the FeedOuptut constructor.
 * @param writer Writer to write the XML representation for the given WireFeed.
 * @param prettyPrint pretty-print XML (true) oder collapsed
 * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed
 *             don't match.
 * @throws IOException thrown if there was some problem writing to the Writer.
 * @throws FeedException thrown if the XML representation for the feed could not be created.
 *
 */
public void output(final WireFeed feed, final Writer writer, final boolean prettyPrint) throws IllegalArgumentException, IOException, FeedException {
    final Document doc = outputJDom(feed);
    final String encoding = feed.getEncoding();
    Format format;
    if (prettyPrint) {
        format = Format.getPrettyFormat();
    } else {
        format = Format.getCompactFormat();
    }
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    final XMLOutputter outputter = new XMLOutputter(format);
    outputter.output(doc, writer);
}
 
Example 20
Source File: NcMLGWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Write a NetcdfDataset as an NcML-G document to the specified stream.
 *
 * @param ncd write this dataset; should have opened with "add coordinates".
 * @param os write to this OutputStream
 * @param showCoords show 1D coordinate values
 * @param uri use this url, if null use getLocation()
 * @throws IOException on io error
 */
public void writeXML(NetcdfDataset ncd, OutputStream os, boolean showCoords, String uri) throws IOException {

  // Output the document, use standard formatter
  // XMLOutputter fmt = new XMLOutputter(" ", true);
  // fmt.setLineSeparator("\n");
  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  fmt.output(makeDocument(ncd, showCoords, uri), os);
}