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.url.impl.GenericURLNormalizer.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//  w  w  w.  ja  va2  s .c  o m
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("urlNormalizer");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeStartElement("normalizations");
        writer.writeCharacters(StringUtils.join(normalizations, ","));
        writer.writeEndElement();
        writer.writeStartElement("replacements");
        for (Replace replace : replaces) {
            writer.writeStartElement("replace");
            writer.writeStartElement("match");
            writer.writeCharacters(replace.getMatch());
            writer.writeEndElement();
            writer.writeStartElement("replacement");
            writer.writeCharacters(replace.getReplacement());
            writer.writeEndElement();
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc??????//from   w w w  .j av a 2s  . c  o  m
 * 
 * @param params
 * @param queryValue
 * @param queryType
 * @return
 * @throws FactoryConfigurationError
 * @throws IOException
 */
protected String convertRequest(SolrParams params, String queryValue, QueryType queryType)
        throws FactoryConfigurationError, IOException {

    String req;
    try {
        CharArrayWriter output = new CharArrayWriter();
        XMLStreamWriter xml = XMLOutputFactory.newInstance().createXMLStreamWriter(output);
        xml.writeStartDocument();
        xml.writeStartElement("gss");
        if (config.settings.gss3version != null) {
            xml.writeAttribute("version", config.settings.gss3version);
        }
        xml.writeStartElement("assoc");
        String target = params.get(PARAM_TARGET, config.defaults.target);
        if (target != null) {
            xml.writeAttribute("target", target);
        }
        convertRequestWriteStage1Param(xml, params);
        convertRequestWriteStage2Param(xml, params);

        convReqWriteQuery(xml, params, queryValue, queryType);

        xml.writeEndElement();
        xml.writeEndElement();
        xml.writeEndDocument();
        xml.close();
        req = output.toString();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }
    LOG.debug(req);
    return req;
}

From source file:jodtemplate.pptx.io.xml.SlideXmlRelsWriter.java

@Override
public void write(final Resources resources, final Slide slide, final XMLOutputFactory xmlOutputFactory)
        throws XMLStreamException, IOException {
    final String slideXmlPath = FilenameUtils
            .normalize(slide.getPresentation().getFullPath() + slide.getRelationship().getTarget(), true);
    final String slideXmlRelsPath = Utils.getRelsPathNoPrefixSeparator(slideXmlPath);
    final Resource slideXmlRelsRes = resources.getResource(slideXmlRelsPath);

    try (final OutputStream os = slideXmlRelsRes.getOutputStream()) {
        os.write(//from w  w  w  .  j  a v a2 s .c  om
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n".getBytes(CharEncoding.UTF_8));
        final XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(os);
        writer.writeStartElement(OOXMLDocument.RELATIONSHIPS_ELEMENT);
        writer.writeNamespace("", OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE);
        for (Relationship rel : slide.getOtherRelationships()) {
            writer.writeEmptyElement(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE,
                    OOXMLDocument.RELATIONSHIP_ELEMENT);
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.ID_ATTRIBUTE,
                    rel.getId());
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.TYPE_ATTRIBUTE,
                    rel.getType());
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.TARGET_ATTRIBUTE,
                    rel.getTarget());
            if (StringUtils.isNotBlank(rel.getTargetMode())) {
                writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE,
                        OOXMLDocument.TARGET_MODE_ATTRIBUTE, rel.getTargetMode());
            }
            writer.flush();
        }
        writer.writeEndElement();
        writer.writeEndDocument();

        writer.flush();
        writer.close();
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.XMLTabularDataConverter.java

@Override
public StreamingOutput createStream(final Result result) {
    StreamingOutput stream = new StreamingOutput() {
        @Override/*w  ww.j ava2s .  co m*/
        public void write(OutputStream outputStream) throws IOException, WebApplicationException {
            ResultSet rs = null;
            XMLStreamWriter xtw = null;
            try {
                rs = (ResultSet) result.getData();
                rs.load(result.getResultSetLocation());
                XMLOutputFactory xof = XMLOutputFactory.newInstance();
                xtw = xof.createXMLStreamWriter(new OutputStreamWriter(outputStream));
                xtw.writeStartDocument("utf-8", "1.0");
                xtw.writeStartElement("results");
                rs.beforeFirst();
                while (rs.next()) {
                    xtw.writeStartElement("result");
                    for (int i = 0; i < rs.getColumnSize(); i++) {
                        xtw.writeStartElement(rs.getColumn(i).getName().replace(" ", "_"));
                        xtw.writeCharacters(rs.getString(i));
                        xtw.writeEndElement();
                    }
                    xtw.writeEndElement();
                }
                xtw.writeEndElement();
                xtw.writeEndDocument();

                xtw.flush();

            } catch (ResultSetException | PersistableException | XMLStreamException e) {
                log.info("Error creating XML Stream: " + e.getMessage());
            } finally {
                if (xtw != null) {
                    try {
                        xtw.close();
                    } catch (XMLStreamException e) {
                        e.printStackTrace();
                    }
                }
                if (rs != null && !rs.isClosed()) {
                    try {
                        rs.close();
                    } catch (ResultSetException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }

        }
    };
    return stream;
}

From source file:net.bulletin.pdi.xero.step.support.XMLChunkerImpl.java

private String pullNextXmlChunkFromTopElementOnStack(XMLChunkerState data) throws KettleException {
    Stack<String> elementStack = data.getElementStack();
    XMLStreamReader xmlStreamReader = data.getXmlStreamReader();

    int elementStackDepthOnEntry = elementStack.size();
    StringWriter stringWriter = new StringWriter();

    try {/*  ww w . j  ava2  s .  c o  m*/
        XMLStreamWriter xmlStreamWriter = data.getXmlOutputFactory().createXMLStreamWriter(stringWriter);

        xmlStreamWriter.writeStartDocument(CharEncoding.UTF_8, "1.0");

        // put the current element on because presumably it's the open element for the one
        // that is being looked for.

        XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);

        while (xmlStreamReader.hasNext() & elementStack.size() >= elementStackDepthOnEntry) {

            switch (xmlStreamReader.next()) {

            case XMLStreamConstants.END_DOCUMENT:
                break; // handled below explicitly.

            case XMLStreamConstants.END_ELEMENT:
                elementStack.pop();
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            case XMLStreamConstants.START_ELEMENT:
                elementStack.push(xmlStreamReader.getLocalName());
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            default:
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            }

        }

        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
    } catch (Exception e) {
        throw new KettleException("unable to process a chunk of the xero xml stream", e);
    }

    return stringWriter.toString();
}

From source file:net.landora.video.info.file.FileInfoManager.java

private synchronized void writeCacheFile(File file, Map<String, FileInfo> infoMap) {
    OutputStream os = null;/* w w  w  . ja  v a2s. com*/
    try {
        os = new BufferedOutputStream(new FileOutputStream(file));
        if (COMPRESS_INFO_FILE) {
            os = new GZIPOutputStream(os);
        }

        XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os);
        writer.writeStartDocument();

        writer.writeStartElement("files");
        writer.writeCharacters("\n");

        for (Map.Entry<String, FileInfo> entry : infoMap.entrySet()) {
            FileInfo info = entry.getValue();

            writer.writeStartElement("file");
            writer.writeAttribute("filename", entry.getKey());

            writer.writeAttribute("ed2k", info.getE2dkHash());
            writer.writeAttribute("length", String.valueOf(info.getFileSize()));
            writer.writeAttribute("lastmodified", String.valueOf(info.getLastModified()));

            if (info.getMetadataSource() != null) {
                writer.writeAttribute("metadatasource", info.getMetadataSource());
            }
            if (info.getMetadataId() != null) {
                writer.writeAttribute("metadataid", info.getMetadataId());
            }
            if (info.getVideoId() != null) {
                writer.writeAttribute("videoid", info.getVideoId());
            }

            writer.writeEndElement();
            writer.writeCharacters("\n");
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.close();

    } catch (Exception e) {
        log.error("Error writing file cache.", e);
    } finally {
        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:com.microsoft.tfs.core.ws.runtime.types.StaxAnyContentType.java

@Override
public void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    FastTempOutputStream ftos = null;/*from  w  w  w . j  a  va 2  s.  c o m*/
    XMLStreamWriter writer = null;

    /*
     * When this method is called, the writer is positioned at the element
     * that contains the "any" content. Process the child elements until the
     * container is done.
     */

    /*
     * Advance one event to get the first child.
     */
    int event = reader.next();

    do {
        if (event == XMLStreamConstants.START_ELEMENT) {
            /*
             * Parse the child element into its own temp file. The copier
             * will read the child's end element.
             */
            try {
                /*
                 * Get a new fast temp output stream.
                 */
                ftos = new FastTempOutputStream(heapStorageLimitBytes, initialHeapStorageSizeBytes);

                tempOutputStreams.add(ftos);

                /*
                 * Create a writer.
                 */
                writer = StaxFactoryProvider.getXMLOutputFactory().createXMLStreamWriter(ftos,
                        SOAPRequestEntity.SOAP_ENCODING);
                writer.writeStartDocument();

                StaxUtils.copyCurrentElement(reader, writer);

                /*
                 * Make sure to finish off the document.
                 */
                writer.writeEndDocument();
            } finally {
                if (writer != null) {
                    writer.close();
                }

                /*
                 * Closing writers does not close the underlying stream, so
                 * close that manually. This is required so the temp stream
                 * can be read from.
                 */
                if (ftos != null) {
                    try {
                        ftos.close();
                    } catch (final IOException e) {
                        log.error(e);
                    }
                }

            }
        }
    } while ((event = reader.next()) != XMLStreamConstants.END_ELEMENT);
}

From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*ww  w . j  a v  a2  s. co m*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("httpClientInitializer");
        writer.writeAttribute("class", getClass().getCanonicalName());

        writeSimpleElement(writer, "cookiesDisabled", Boolean.toString(cookiesDisabled));
        writeSimpleElement(writer, "userAgent", userAgent);
        writeSimpleElement(writer, "authMethod", authMethod);
        writeSimpleElement(writer, "authUsername", authUsername);
        writeSimpleElement(writer, "authPassword", authPassword);
        writeSimpleElement(writer, "authUsernameField", authUsernameField);
        writeSimpleElement(writer, "authPasswordField", authPasswordField);
        writeSimpleElement(writer, "authURL", authURL);
        writeSimpleElement(writer, "authHostname", authHostname);
        writeSimpleElement(writer, "authPort", Integer.toString(authPort));
        writeSimpleElement(writer, "authRealm", authRealm);
        writeSimpleElement(writer, "proxyHost", proxyHost);
        writeSimpleElement(writer, "proxyPort", Integer.toString(proxyPort));
        writeSimpleElement(writer, "proxyUsername", proxyUsername);
        writeSimpleElement(writer, "proxyPassword", proxyPassword);
        writeSimpleElement(writer, "proxyRealm", proxyRealm);
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.norconex.collector.http.delay.impl.DefaultDelayResolver.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*from ww w.  j  a  va  2  s  .  co m*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("delay");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("default", Long.toString(defaultDelay));
        writer.writeAttribute("scope", scope);
        writer.writeAttribute("ignoreRobotsCrawlDelay", Boolean.toString(ignoreRobotsCrawlDelay));

        for (DelaySchedule schedule : schedules) {
            writer.writeStartElement("schedule");
            if (schedule.getDayOfWeekRange() != null) {
                writer.writeAttribute("dayOfWeek", "from " + schedule.getDayOfWeekRange().getMinimum() + " to "
                        + schedule.getDayOfWeekRange().getMaximum());
            }
            if (schedule.getDayOfMonthRange() != null) {
                writer.writeAttribute("dayOfMonth", "from " + schedule.getDayOfMonthRange().getMinimum()
                        + " to " + schedule.getDayOfMonthRange().getMaximum());
            }
            if (schedule.getTimeRange() != null) {
                writer.writeAttribute("time", "from " + schedule.getTimeRange().getLeft().toString("HH:MM")
                        + " to " + schedule.getTimeRange().getRight().toString("HH:MM"));
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

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

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);

    if (lockToken != null) {
        request.addHeader("If", "<" + uri + "> (<" + lockToken + ">)");
    }/* w  ww  .  j  a v  a  2s  . c o  m*/

    final Writer body = new StringBuilderWriter();
    try {
        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.setPrefix(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeStartElement(type.action);
        writer.writeStartElement("prop");
        for (final ResourceProperty property : properties) {
            final String prefix = property.getType().getPrefix();
            if (type == Type.SET) {
                writer.writeStartElement(prefix, ResourcePropertyUtils.escapedKeyNameXml(property.getName()));
                writer.writeCharacters(property.getValue());
                writer.writeEndElement();
            } else {
                writer.writeEmptyElement(prefix, property.getName());
            }
        }
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set || delete
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final String bodyWithMakers = body.toString();
    final String bodyWithoutMakers = ResourcePropertyUtils.filterMarker(bodyWithMakers);
    request.setEntity(new StringEntity(bodyWithoutMakers, CONTENT_TYPE_XML));
    return request;
}