Example usage for javax.xml.stream XMLStreamWriter close

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

Introduction

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

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Close this writer and free any resources associated with the writer.

Usage

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//w ww . ja v  a  2  s . com
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("sitemap");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("lenient", Boolean.toString(lenient));
        if (sitemapLocations != null) {
            for (String location : sitemapLocations) {
                writer.writeStartElement("location");
                writer.writeCharacters(location);
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

public TcLogInfo parse(BuildListener listener) {
    try {//from  w  ww  .  java  2s . com
        ZipFile logArchive = new ZipFile(log);

        Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                DESCRIPTION_ENTRY_NAME);
        if (descriptionTopLevelNode == null) {
            throw new ParsingException("Unable to obtain description top-level node.");
        }

        long startTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, START_TIME_PROPERTY_NAME));
        long stopTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, STOP_TIME_PROPERTY_NAME));

        int testCount = 0;
        try {
            testCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, TEST_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int warningCount = 0;
        try {
            warningCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, WARNING_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int errorCount = 0;
        try {
            errorCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, ERROR_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        TcLogInfo logInfo = new TcLogInfo(startTime, stopTime, testCount, errorCount, warningCount);

        String xml = null;

        if (generateJUnitReports) {
            XMLStreamWriter xmlStreamWriter = null;
            try {
                StringWriter stringWriter = new StringWriter();
                xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
                convertToXML(logArchive, logInfo, xmlStreamWriter);
                xmlStreamWriter.flush();
                xmlStreamWriter.close();
                xmlStreamWriter = null;
                xml = stringWriter.toString();
            } catch (Exception e) {
                TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
            } finally {
                if (xmlStreamWriter != null) {
                    xmlStreamWriter.close();
                }
            }
        }

        logInfo.setXML(xml);

        return logInfo;
    } catch (Exception e) {
        TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
        return null;
    }
}

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

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {//from ww w .  ja va  2s  .com
        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: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 ww  .j  a  va 2s  .  co  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: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   ww  w  .ja va  2  s. c  o  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.cloud.bridge.service.controller.s3.S3ObjectAction.java

private void executeGetObjectAcl(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);

    S3GetObjectAccessControlPolicyRequest engineRequest = new S3GetObjectAccessControlPolicyRequest();
    engineRequest.setBucketName(bucketName);
    engineRequest.setKey(key);/*  ww w.ja v a  2s  .  c  om*/

    S3AccessControlPolicy engineResponse = ServiceProvider.getInstance().getS3Engine()
            .handleRequest(engineRequest);

    // -> serialize using the apache's Axiom classes
    GetObjectAccessControlPolicyResponse onePolicy = S3SoapServiceImpl
            .toGetObjectAccessControlPolicyResponse(engineResponse);

    try {
        OutputStream os = response.getOutputStream();
        response.setStatus(200);
        response.setContentType("text/xml; charset=UTF-8");
        XMLStreamWriter xmlWriter = xmlOutFactory.createXMLStreamWriter(os);
        String documentStart = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        os.write(documentStart.getBytes());
        MTOMAwareXMLSerializer MTOMWriter = new MTOMAwareXMLSerializer(xmlWriter);
        onePolicy.serialize(new QName("http://s3.amazonaws.com/doc/2006-03-01/",
                "GetObjectAccessControlPolicyResponse", "ns1"), factory, MTOMWriter);
        xmlWriter.flush();
        xmlWriter.close();
        os.close();
    } catch (XMLStreamException e) {
        throw new IOException(e.toString());
    }
}

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

/**
 * Get this metadata object as XML document
 *
 * @return XML document/*ww w .  ja  v a 2  s . c o m*/
 * @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:de.shadowhunt.subversion.internal.LogOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {//from   w  ww  . ja va2 s  .  co 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;
}

From source file:com.fiorano.openesb.application.DmiObject.java

/**
 * Writes this object to specified filename
 * @param fileName file name//  www . j  a va2  s.  c o m
 * @throws FioranoException FioranoException
 */
public void toXMLString(String fileName) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    FileOutputStream fos = null;
    XMLStreamWriter writer = null;
    try {
        try {
            fos = new FileOutputStream(fileName);
            writer = outputFactory.createXMLStreamWriter(fos);
            toJXMLString(writer);
            writer.flush();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (XMLStreamException e) {
                // Ignore
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    }

}

From source file:com.fiorano.openesb.application.DmiObject.java

public void toXMLString(String fileName, boolean writeCDataSections) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    FileOutputStream fos = null;//from  w w w .j  a va2  s.c  om
    XMLStreamWriter writer = null;
    try {
        try {
            fos = new FileOutputStream(fileName);
            writer = outputFactory.createXMLStreamWriter(fos);
            toJXMLString(writer, writeCDataSections);
            writer.flush();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (XMLStreamException e) {
                // Ignore
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    }
}