Example usage for javax.xml.stream XMLStreamWriter writeEndDocument

List of usage examples for javax.xml.stream XMLStreamWriter writeEndDocument

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter writeEndDocument.

Prototype

public void writeEndDocument() throws XMLStreamException;

Source Link

Document

Closes any start tags and writes corresponding end tags.

Usage

From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java

public static void write(List<Scale> modeList, String fileName) {
    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLStreamWriter xtw = null;

    // <mode>
    // <name>Peruvian tritonic 2</name>
    // <interval>3</interval>
    // <interval>4</interval>
    // <interval>5</interval>
    // </mode>

    String ns = "http://rockhoppertech.com/modes-1.0";

    // StringWriter sw = new StringWriter();
    try {/*from w  w w . jav  a2 s . com*/
        xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
        // xtw = xof.createXMLStreamWriter(sw);
        xtw.writeComment("all elements here are explicitly in the mode namespace");
        xtw.writeStartDocument("utf-8", "1.0");
        xtw.setPrefix("modes", ns);
        xtw.writeStartElement(ns, "modes");
        xtw.writeNamespace("modes", ns);

        for (Scale scale : modeList) {
            // xtw.writeStartElement(ns, "mode");
            xtw.writeStartElement("mode");

            // xtw.writeStartElement(ns, "name");
            xtw.writeStartElement("name");
            xtw.writeCharacters(scale.getName());
            xtw.writeEndElement();

            // xtw.writeStartElement(ns, "intervals");
            // xtw.writeStartElement(ns, "interval");
            xtw.writeStartElement("intervals");
            int[] intervals = scale.getIntervals();
            for (int i = 0; i < intervals.length; i++) {
                xtw.writeStartElement("interval");
                xtw.writeCharacters("" + intervals[i]);
                xtw.writeEndElement();
            }
            xtw.writeEndElement(); // intervals

            xtw.writeEndElement(); // mode
        }

        xtw.writeEndElement(); // modes
        xtw.writeEndDocument();
        xtw.flush();
        xtw.close();
        // System.err.println(sw.toString());

    } catch (XMLStreamException | IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        e.printStackTrace();
    }

}

From source file:eu.interedition.collatex.tools.CollationServer.java

public void service(Request request, Response response) throws Exception {
    final Deque<String> path = path(request);
    if (path.isEmpty() || !"collate".equals(path.pop())) {
        response.sendError(404);/*from w  w  w .  j  a  v a 2 s.c  o  m*/
        return;
    }

    final SimpleCollation collation = JsonProcessor.read(request.getInputStream());
    if (maxCollationSize > 0) {
        for (SimpleWitness witness : collation.getWitnesses()) {
            final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken)
                    .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum();
            if (witnessLength > maxCollationSize) {
                response.sendError(413, "Request Entity Too Large");
                return;
            }
        }
    }

    response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>());
    collationThreads.submit(() -> {
        try {
            final VariantGraph graph = new VariantGraph();
            collation.collate(graph);

            // CORS support
            response.setHeader("Access-Control-Allow-Origin",
                    Optional.ofNullable(request.getHeader("Origin")).orElse("*"));
            response.setHeader("Access-Control-Allow-Methods",
                    Optional.ofNullable(request.getHeader("Access-Control-Request-Method"))
                            .orElse("GET, POST, HEAD, OPTIONS"));
            response.setHeader("Access-Control-Allow-Headers",
                    Optional.ofNullable(request.getHeader("Access-Control-Request-Headers"))
                            .orElse("Content-Type, Accept, X-Requested-With"));
            response.setHeader("Access-Control-Max-Age", "86400");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse("");

            if (clientAccepts.contains("text/plain")) {
                response.setContentType("text/plain");
                response.setCharacterEncoding("utf-8");
                try (final Writer out = response.getWriter()) {
                    new SimpleVariantGraphSerializer(graph).toDot(out);
                }
                response.resume();

            } else if (clientAccepts.contains("application/tei+xml")) {
                XMLStreamWriter xml = null;
                try {
                    response.setContentType("application/tei+xml");
                    try (OutputStream responseStream = response.getOutputStream()) {
                        xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream);
                        xml.writeStartDocument();
                        new SimpleVariantGraphSerializer(graph).toTEI(xml);
                        xml.writeEndDocument();
                    } finally {
                        if (xml != null) {
                            xml.close();
                        }
                    }
                    response.resume();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            } else if (clientAccepts.contains("application/graphml+xml")) {
                XMLStreamWriter xml = null;
                try {
                    response.setContentType("application/graphml+xml");
                    try (OutputStream responseStream = response.getOutputStream()) {
                        xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream);
                        xml.writeStartDocument();
                        new SimpleVariantGraphSerializer(graph).toGraphML(xml);
                        xml.writeEndDocument();
                    } finally {
                        if (xml != null) {
                            xml.close();
                        }
                    }
                    response.resume();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            } else if (clientAccepts.contains("image/svg+xml")) {
                if (dotPath == null) {
                    response.sendError(204);
                    response.resume();
                } else {
                    final StringWriter dot = new StringWriter();
                    new SimpleVariantGraphSerializer(graph).toDot(dot);

                    final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph",
                            "-Tsvg").start();
                    final StringWriter errors = new StringWriter();
                    CompletableFuture.allOf(CompletableFuture.runAsync(() -> {
                        final char[] buf = new char[8192];
                        try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) {
                            int len;
                            while ((len = errorStream.read(buf)) >= 0) {
                                errors.write(buf, 0, len);
                            }
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(),
                                "UTF-8")) {
                            dotProcStream.write(dot.toString());
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        response.setContentType("image/svg+xml");
                        final byte[] buf = new byte[8192];
                        try (final InputStream in = dotProc.getInputStream();
                                final OutputStream out = response.getOutputStream()) {
                            int len;
                            while ((len = in.read(buf)) >= 0) {
                                out.write(buf, 0, len);
                            }
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        try {
                            if (!dotProc.waitFor(60, TimeUnit.SECONDS)) {
                                throw new CompletionException(new RuntimeException(
                                        "dot processing took longer than 60 seconds, process was timed out."));
                            }
                            if (dotProc.exitValue() != 0) {
                                throw new CompletionException(new IllegalStateException(errors.toString()));
                            }
                        } catch (InterruptedException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads)).exceptionally(t -> {
                        t.printStackTrace();
                        return null;
                    }).thenRunAsync(response::resume, processThreads);
                }
            } else {
                response.setContentType("application/json");
                try (final OutputStream responseStream = response.getOutputStream()) {
                    JsonProcessor.write(graph, responseStream);
                }
                response.resume();
            }
        } catch (IOException e) {
            // FIXME: ignored
        }
    });
}

From source file:de.qucosa.webapi.v1.RelationResource.java

@RequestMapping(value = "/relation/urn/{URN}", method = RequestMethod.GET)
public ResponseEntity<String> describeRelationships(@PathVariable String URN)
        throws XMLStreamException, IOException, FedoraClientException {
    String pid = fedoraRepository.getPIDByIdentifier(URN);
    List<Tuple<String>> constituentPredecessorPids = fedoraRepository.getPredecessorPIDs(pid,
            FedoraRepository.RELATION_CONSTITUENT);
    List<Tuple<String>> derivativePredecessorPIDs = fedoraRepository.getPredecessorPIDs(pid,
            FedoraRepository.RELATION_DERIVATIVE);
    List<Tuple<String>> constituentSuccessorPids = fedoraRepository.getSuccessorPIDs(pid,
            FedoraRepository.RELATION_CONSTITUENT);
    List<Tuple<String>> derivativeSuccessorPids = fedoraRepository.getSuccessorPIDs(pid,
            FedoraRepository.RELATION_DERIVATIVE);

    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeStartElement("Opus_Document");
    w.writeStartElement("DocumentId");
    w.writeCharacters(stripPrefix(pid));
    w.writeEndElement();/*from w w  w . jav a 2 s  .c  o m*/
    w.writeStartElement("Relations");
    writeRelationElement(constituentPredecessorPids, w, "PredecessorRelation", "journal");
    writeRelationElement(derivativePredecessorPIDs, w, "PredecessorRelation", "predecessor");
    writeRelationElement(constituentSuccessorPids, w, "SuccessorRelation", "issue");
    writeRelationElement(derivativeSuccessorPids, w, "SuccessorRelation", "predecessor");
    w.writeEndElement();
    w.writeEndElement();
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

    return new ResponseEntity<>(sw.toString(), HttpStatus.OK);
}

From source file:de.huxhorn.sulky.plist.impl.PropertyListWriter.java

public void write(XMLStreamWriter writer, PropertyList object, boolean isRoot) throws XMLStreamException {
    if (isRoot) {
        writer.writeStartDocument("utf-8", "1.0");
        writer.writeCharacters("\n");
        writer.writeDTD(/*  w w w .  j  a  va  2s .co m*/
                "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
        writer.writeCharacters("\n");
    }
    StaxUtilities.writeStartElement(writer, null, null, PLIST_NODE);
    StaxUtilities.writeAttribute(writer, false, null, null, PLIST_VERSION_ATTRIBUTE, PLIST_VERSION);

    if (object != null) {
        writeValue(writer, object.getRoot());
    }

    writer.writeEndElement();
    if (isRoot) {
        writer.writeEndDocument();
    }
}

From source file:de.shadowhunt.subversion.internal.CommitMessageOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {/*from w ww.  ja  va2s  . c o  m*/
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propertyupdate");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("set");
        writer.writeStartElement("prop");
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeStartElement(XmlConstants.SUBVERSION_DAV_NAMESPACE, "log");
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeCharacters(message);
        writer.writeEndElement(); // log
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:org.xmlsh.internal.commands.http.java

private void writeHeaders(String outv, StatusLine statusLine, Header[] allHeaders)
        throws XMLStreamException, SaxonApiException, CoreException, IOException {
    OutputPort out = mShell.getEnv().getOutputPort(outv);

    XMLStreamWriter sw = out.asXMLStreamWriter(getSerializeOpts());
    sw.writeStartDocument();/*from w  w w . jav  a 2 s  .co m*/
    sw.writeStartElement("status");
    sw.writeAttribute("status-code", String.valueOf(statusLine.getStatusCode()));
    sw.writeAttribute("reason", statusLine.getReasonPhrase());
    sw.writeAttribute("protocol-version", statusLine.getProtocolVersion().toString());

    sw.writeEndElement();

    sw.writeStartElement("headers");
    for (Header header : allHeaders) {
        sw.writeStartElement("header");
        sw.writeAttribute("name", header.getName());
        sw.writeAttribute("value", header.getValue());
        sw.writeEndElement();
    }
    sw.writeEndElement();
    sw.writeEndDocument();
    sw.close();

}

From source file:com.flexive.shared.media.FxMetadata.java

/**
 * Get this metadata object as XML document
 *
 * @return XML document/*  w w  w  .  j  av  a 2s .c  om*/
 * @throws FxApplicationException on errors
 */
public String toXML() throws FxApplicationException {
    StringWriter sw = new StringWriter(2000);
    try {
        XMLStreamWriter writer = getXmlOutputFactory().createXMLStreamWriter(sw);
        writer.writeStartDocument();
        writer.writeStartElement("metadata");
        writer.writeAttribute("mediatype", getMediaType().name());
        writer.writeAttribute("mimetype", getMimeType());
        writer.writeAttribute("filename", getFilename());
        writeXMLTags(writer);
        for (FxMetadataItem mdi : getMetadata()) {
            final String value = mdi.getValue().replaceAll("[\\x00-\\x1F]", ""); //filter out control characters
            if (StringUtils.isEmpty(value))
                continue;
            writer.writeStartElement("meta");
            writer.writeAttribute("key", mdi.getKey());
            writer.writeCData(value);
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new FxApplicationException(e, "ex.general.xml", e.getMessage());
    }
    return sw.getBuffer().toString();
}

From source file:XMLWriteTest.java

/**
 * Writers an SVG document of the current drawing.
 * @param writer the document destination
 *//*from   w w  w.j av a  2 s .  co  m*/
public void writeDocument(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartDocument();
    writer.writeDTD("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 20000802//EN\" "
            + "\"http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd\">");
    writer.writeStartElement("svg");
    writer.writeAttribute("width", "" + getWidth());
    writer.writeAttribute("height", "" + getHeight());
    for (int i = 0; i < rects.size(); i++) {
        Color c = colors.get(i);
        Rectangle2D r = rects.get(i);
        writer.writeEmptyElement("rect");
        writer.writeAttribute("x", "" + r.getX());
        writer.writeAttribute("y", "" + r.getY());
        writer.writeAttribute("width", "" + r.getWidth());
        writer.writeAttribute("height", "" + r.getHeight());
        writer.writeAttribute("fill", colorToString(c));
    }
    writer.writeEndDocument(); // closes svg element
}

From source file:com.github.lindenb.jvarkit.tools.bam2xml.Bam2Xml.java

private int run(SamReader samReader) {
    OutputStream fout = null;/*from w  w w  .  j  av  a 2  s.c  o  m*/
    SAMRecordIterator iter = null;
    XMLStreamWriter w = null;
    try {
        XMLOutputFactory xmlfactory = XMLOutputFactory.newInstance();

        if (getOutputFile() != null) {
            fout = IOUtils.openFileForWriting(getOutputFile());
            w = xmlfactory.createXMLStreamWriter(fout, "UTF-8");
        } else {
            w = xmlfactory.createXMLStreamWriter(stdout(), "UTF-8");
        }
        w.writeStartDocument("UTF-8", "1.0");
        final SAMFileHeader header = samReader.getFileHeader();
        final SAMXMLWriter xw = new SAMXMLWriter(w, header);
        final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header);
        iter = samReader.iterator();
        while (iter.hasNext()) {
            xw.addAlignment(progress.watch(iter.next()));
        }
        xw.close();
        w.writeEndDocument();
        if (fout != null)
            fout.flush();
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e);
        return -1;
    } finally {
        CloserUtil.close(w);
        CloserUtil.close(iter);
        CloserUtil.close(fout);
    }
    return 0;
}

From source file:de.shadowhunt.subversion.internal.LogOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {//www .j  a v a  2  s.  c o  m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("log-report");
        writer.writeDefaultNamespace(XmlConstants.SVN_NAMESPACE);
        writer.writeStartElement("start-revision");
        writer.writeCharacters(start.toString());
        writer.writeEndElement(); // start-revision
        writer.writeStartElement("end-revision");
        writer.writeCharacters(end.toString());
        writer.writeEndElement(); // end-revision
        if (limit > 0) {
            writer.writeStartElement("limit");
            writer.writeCharacters(Integer.toString(limit));
            writer.writeEndElement(); // limit
        }
        writer.writeEmptyElement("discover-changed-paths");
        writer.writeEmptyElement("all-revprops");
        writer.writeEmptyElement("path");
        writer.writeEndElement(); // log-report
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("REPORT", uri);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}