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:de.shadowhunt.subversion.internal.MergeOperation.java

@Override
protected HttpUriRequest createRequest() {
    final DavTemplateRequest request = new DavTemplateRequest("MERGE", repository);
    request.addHeader("X-SVN-Options", "release-locks");

    final Writer body = new StringBuilderWriter();
    try {/*  w  w w . j  a  v  a2 s.  c o m*/
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("merge");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("source");
        writer.writeStartElement("href");
        writer.writeCData(repository.getPath() + resource.getValue());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // source
        writer.writeEmptyElement("no-auto-merge");
        writer.writeEmptyElement("no-checkout");
        writer.writeStartElement("prop");
        writer.writeEmptyElement("checked-in");
        writer.writeEmptyElement("version-name");
        writer.writeEmptyElement("resourcetype");
        writer.writeEmptyElement("creationdate");
        writer.writeEmptyElement("creator-displayname");
        writer.writeEndElement(); // prop
        if (!infoSet.isEmpty()) {
            writer.setPrefix(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token-list");
            writer.writeNamespace(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            for (final Info info : infoSet) {
                final String lockToken = info.getLockToken();
                assert (lockToken != null) : "must not be null";
                final Resource infoResource = info.getResource();

                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock");
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-path");
                writer.writeCData(infoResource.getValueWithoutLeadingSeparator());
                writer.writeEndElement(); // lock-path
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token");
                writer.writeCharacters(lockToken);
                writer.writeEndElement(); // lock-token
                writer.writeEndElement(); // lock
            }
            writer.writeEndElement(); // lock-token-list
        }
        writer.writeEndElement(); // merge
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * This method creates the XMI file. Created content is:<br/>
 * <code>&lt;?xml version="{@link XMIConstants4SchemaGraph2XMI#XML_VERSION}" encoding="{@link XMIConstants4SchemaGraph2XMI#XML_ENCODING}"?&gt;<br/>
 * &lt;!-- content created by {@link SchemaGraph2XMI#createRootElement(XMLStreamWriter, SchemaGraph)} --&gt;
 * </code>//  w ww  .  j  a va  2  s.  c o  m
 * 
 * @param xmiName
 *            {@link String} the path of the XMI file
 * @param schemaGraph
 *            {@link SchemaGraph} to be converted into an XMI
 * @throws XMLStreamException
 * @throws IOException
 */
private void createXMI(String xmiName, SchemaGraph schemaGraph) throws XMLStreamException, IOException {
    Writer out = null;
    XMLStreamWriter writer = null;
    try {
        // create the XMLStreamWriter which creates the current xmi-file.
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmiName), "UTF-8"));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
        writer = factory.createXMLStreamWriter(out);

        // write the first line
        writer.writeStartDocument(XMIConstants4SchemaGraph2XMI.XML_ENCODING,
                XMIConstants4SchemaGraph2XMI.XML_VERSION);
        createRootElement(writer, schemaGraph);
        // write the end of the document
        writer.writeEndDocument();

        // close the XMLStreamWriter
        writer.flush();
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // no handling of exceptions, because they are throw as mentioned in
        // the declaration.
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * StAX for efficient streaming XML writing.
 * /*  ww w. j a  va 2 s  .c  o  m*/
 * @throws IOException
 * @throws XMLStreamException 
 */
private static void writeProfile(String dname, String fname) throws IOException, XMLStreamException {
    //create initial directory and file 
    File dir = new File(dname);
    if (!dir.exists())
        dir.mkdir();
    File f = new File(fname);
    f.createNewFile();

    FileOutputStream fos = new FileOutputStream(f);

    try {
        //create document
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(fos);
        //TODO use an alternative way for intentation
        //xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required

        //write document content
        xsw.writeStartDocument();
        xsw.writeStartElement(XML_PROFILE);
        xsw.writeAttribute(XML_DATE, String.valueOf(new Date()));

        //foreach instruction (boundle of cost functions)
        for (Entry<Integer, HashMap<Integer, CostFunction>> inst : _profile.entrySet()) {
            int instID = inst.getKey();
            String instName = _regInst_IDNames.get(instID);

            xsw.writeStartElement(XML_INSTRUCTION);
            xsw.writeAttribute(XML_ID, String.valueOf(instID));
            xsw.writeAttribute(XML_NAME, instName.replaceAll(Lop.OPERAND_DELIMITOR, " "));

            //foreach testdef cost function
            for (Entry<Integer, CostFunction> cfun : inst.getValue().entrySet()) {
                int tdefID = cfun.getKey();
                PerfTestDef def = _regTestDef.get(tdefID);
                CostFunction cf = cfun.getValue();

                xsw.writeStartElement(XML_COSTFUNCTION);
                xsw.writeAttribute(XML_ID, String.valueOf(tdefID));
                xsw.writeAttribute(XML_MEASURE, def.getMeasure().toString());
                xsw.writeAttribute(XML_VARIABLE, def.getVariable().toString());
                xsw.writeAttribute(XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()));
                xsw.writeAttribute(XML_DATAFORMAT, def.getDataformat().toString());
                xsw.writeCharacters(serializeParams(cf.getParams()));
                xsw.writeEndElement();// XML_COSTFUNCTION
            }

            xsw.writeEndElement(); //XML_INSTRUCTION
        }

        xsw.writeEndElement();//XML_PROFILE
        xsw.writeEndDocument();
        xsw.close();
    } finally {
        IOUtilFunctions.closeSilently(fos);
    }
}

From source file:de.codesourcery.eve.skills.dao.impl.FileShoppingListDAO.java

protected void writeToFile() {

    XMLStreamWriter writer = null;
    try {/*  w  w  w.  j  av a  2  s .c o m*/

        if (!dataFile.exists()) {
            final File parent = dataFile.getParentFile();
            if (parent != null && !parent.exists()) {
                if (!parent.mkdirs()) {
                    log.error("writeToFile(): Failed to create parent directory " + parent.getAbsolutePath());
                } else {
                    log.info("writeToFile(): Created parent directory " + parent.getAbsolutePath());
                }
            }
        }

        final XMLOutputFactory factory = XMLOutputFactory.newInstance();

        log.info("writeToFile(): Writing to " + dataFile.getAbsolutePath());
        final FileOutputStream outStream = new FileOutputStream(dataFile);
        writer = factory.createXMLStreamWriter(outStream, OUTPUT_ENCODING);

        writer.writeStartDocument(OUTPUT_ENCODING, "1.0");
        writer.writeStartElement("shoppinglists"); // <shoppinglists>
        synchronized (this.entries) {
            for (ShoppingList list : this.entries) {
                writer.writeStartElement("shoppinglist");
                writer.writeAttribute("title", list.getTitle());
                if (!StringUtils.isBlank(list.getDescription())) {
                    writer.writeStartElement("description");
                    writer.writeCharacters(list.getDescription());
                    writer.writeEndElement(); // </description>
                }

                writer.writeStartElement("entries");
                for (ShoppingListEntry entry : list.getEntries()) {
                    writer.writeStartElement("entry");
                    writer.writeAttribute("itemId", Long.toString(entry.getType().getId()));
                    writer.writeAttribute("totalQuantity", Long.toString(entry.getQuantity()));
                    writer.writeAttribute("purchasedQuantity", Long.toString(entry.getPurchasedQuantity()));

                    writer.writeEndElement(); // </entry>
                }
                writer.writeEndElement(); // </entries>
                writer.writeEndElement(); // </shoppinglist>
            }
        }
        writer.writeEndElement(); // </shoppinglists>
        writer.writeEndDocument();

        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } catch (XMLStreamException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                log.error("writeToFile(): Caught ", e);
            }
        }
    }
}

From source file:com.norconex.committer.core.AbstractMappedCommitter.java

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

        if (sourceReferenceField != null) {
            writer.writeStartElement("sourceReferenceField");
            writer.writeAttribute("keep", Boolean.toString(keepSourceReferenceField));
            writer.writeCharacters(sourceReferenceField);
            writer.writeEndElement();
        }
        if (targetReferenceField != null) {
            writer.writeStartElement("targetReferenceField");
            writer.writeCharacters(targetReferenceField);
            writer.writeEndElement();
        }
        if (sourceContentField != null) {
            writer.writeStartElement("sourceContentField");
            writer.writeAttribute("keep", Boolean.toString(keepSourceContentField));
            writer.writeCharacters(sourceContentField);
            writer.writeEndElement();
        }
        if (targetContentField != null) {
            writer.writeStartElement("targetContentField");
            writer.writeCharacters(targetContentField);
            writer.writeEndElement();
        }
        if (getQueueDir() != null) {
            writer.writeStartElement("queueDir");
            writer.writeCharacters(getQueueDir());
            writer.writeEndElement();
        }
        writer.writeStartElement("queueSize");
        writer.writeCharacters(ObjectUtils.toString(getQueueSize()));
        writer.writeEndElement();

        writer.writeStartElement("commitBatchSize");
        writer.writeCharacters(ObjectUtils.toString(getCommitBatchSize()));
        writer.writeEndElement();

        writer.writeStartElement("maxRetries");
        writer.writeCharacters(ObjectUtils.toString(getMaxRetries()));
        writer.writeEndElement();

        writer.writeStartElement("maxRetryWait");
        writer.writeCharacters(ObjectUtils.toString(getMaxRetryWait()));
        writer.writeEndElement();

        saveToXML(writer);

        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:edu.jhu.pha.vospace.node.Node.java

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {/*from  w  w  w .  jav a 2s  . c o  m*/
        XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter);
        xsw.writeStartDocument();

        xsw.setDefaultNamespace(VOS_NAMESPACE);

        xsw.writeStartElement("node");
        xsw.writeNamespace("xsi", XSI_NAMESPACE);
        xsw.writeNamespace(null, VOS_NAMESPACE);
        xsw.writeAttribute("xsi:type", this.getType().getTypeName());
        xsw.writeAttribute("uri", this.getUri().toString());

        if (detail == Detail.max) {
            xsw.writeStartElement("properties");
            Map<String, String> properties = this.getMetastore().getProperties(this.getUri());
            properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize()));
            properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime()));
            if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE
                    || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) {
                properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType());
            }

            for (String propUri : properties.keySet()) {
                xsw.writeStartElement("property");
                xsw.writeAttribute("uri", propUri);
                xsw.writeCharacters(properties.get(propUri));
                xsw.writeEndElement();
            }

            xsw.writeEndElement();

            xsw.writeStartElement("accepts");
            xsw.writeEndElement();

            xsw.writeStartElement("provides");
            xsw.writeEndElement();

            xsw.writeStartElement("capabilities");
            xsw.writeEndElement();

            if (this.getType() == NodeType.CONTAINER_NODE) {
                NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1);
                List<Node> children = childrenList.getNodesList();

                xsw.writeStartElement("nodes");
                for (Node childNode : children) {
                    xsw.writeStartElement("node");
                    xsw.writeAttribute("uri", childNode.getUri().getId().toString());
                    xsw.writeEndElement();
                }
                xsw.writeEndElement();

            }

        }

        xsw.writeEndElement();

        xsw.writeEndDocument();
        xsw.close();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    }
    return jobWriter.getBuffer().toString();
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String removeLocalization(String xml, String key, String requestedLanguageId, boolean cdata,
        boolean localized) {

    if (Validator.isNull(xml)) {
        return StringPool.BLANK;
    }/*  w w w  .ja  v  a  2  s. c o m*/

    xml = _sanitizeXML(xml);

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;
        String defaultLanguageId = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);
            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        if ((availableLocales != null) && (availableLocales.indexOf(requestedLanguageId) != -1)) {

            availableLocales = StringUtil.remove(availableLocales, requestedLanguageId, StringPool.COMMA);

            UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

            xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

            xmlStreamWriter.writeStartDocument();
            xmlStreamWriter.writeStartElement(_ROOT);

            if (localized) {
                xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
                xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
            }

            _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndDocument();

            xmlStreamWriter.close();
            xmlStreamWriter = null;

            xml = unsyncStringWriter.toString();
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

From source file:org.sfs.nodes.compute.container.GetContainer.java

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();
    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAuthenticated(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateContainerPath())
            .flatMap(new LoadAccountAndContainer(vertxContext))
            .flatMap(new ValidateActionContainerListObjects(httpServerRequest)).flatMap(persistentContainer -> {

                HttpServerResponse httpServerResponse = httpServerRequest.response();

                MultiMap queryParams = httpServerRequest.params();
                MultiMap headerParams = httpServerRequest.headers();

                String format = queryParams.get(FORMAT);
                String accept = headerParams.get(ACCEPT);

                MediaType parsedAccept = null;

                if (equalsIgnoreCase("xml", format)) {
                    parsedAccept = APPLICATION_XML_UTF_8;
                } else if (equalsIgnoreCase("json", format)) {
                    parsedAccept = JSON_UTF_8;
                }/*from  w  ww . j  a v a2  s  .c om*/

                if (parsedAccept == null) {
                    if (!isNullOrEmpty(accept)) {
                        parsedAccept = parse(accept);
                    }
                }

                if (parsedAccept == null || (!PLAIN_TEXT_UTF_8.is(parsedAccept)
                        && !APPLICATION_XML_UTF_8.is(parsedAccept) && !JSON_UTF_8.equals(parsedAccept))) {
                    parsedAccept = PLAIN_TEXT_UTF_8;
                }

                Observable<Optional<ContainerStats>> oContainerStats;
                boolean hasPrefix = !Strings.isNullOrEmpty(queryParams.get(SfsHttpQueryParams.PREFIX));
                if (hasPrefix) {
                    oContainerStats = just(persistentContainer)
                            .flatMap(new LoadContainerStats(httpServerRequest.vertxContext()))
                            .map(Optional::of);
                } else {
                    oContainerStats = Defer.just(Optional.<ContainerStats>absent());
                }

                Observable<ObjectList> oObjectListing = just(persistentContainer)
                        .flatMap(new ListObjects(httpServerRequest));

                MediaType finalParsedAccept = parsedAccept;
                return combineSinglesDelayError(oContainerStats, oObjectListing,
                        (containerStats, objectList) -> {

                            if (containerStats.isPresent()) {

                                Metadata metadata = persistentContainer.getMetadata();

                                for (String key : metadata.keySet()) {
                                    SortedSet<String> values = metadata.get(key);
                                    if (values != null && !values.isEmpty()) {
                                        httpServerResponse.putHeader(
                                                format("%s%s", X_ADD_CONTAINER_META_PREFIX, key), values);
                                    }
                                }

                                httpServerResponse.putHeader(X_CONTAINER_OBJECT_COUNT,
                                        valueOf(containerStats.get().getObjectCount()));
                                httpServerResponse.putHeader(X_CONTAINER_BYTES_USED,
                                        BigDecimal.valueOf(containerStats.get().getBytesUsed())
                                                .setScale(0, ROUND_HALF_UP).toString());
                            }

                            BufferOutputStream bufferOutputStream = new BufferOutputStream();

                            if (JSON_UTF_8.is(finalParsedAccept)) {

                                try {
                                    JsonFactory jsonFactory = vertxContext.verticle().jsonFactory();
                                    JsonGenerator jg = jsonFactory.createGenerator(bufferOutputStream, UTF8);
                                    jg.writeStartArray();

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        jg.writeStartObject();
                                        jg.writeStringField("hash",
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        jg.writeStringField("last_modified",
                                                toDateTimeString(listedObject.getLastModified()));
                                        jg.writeNumberField("bytes", listedObject.getLength());
                                        jg.writeStringField("content_type", listedObject.getContentType());
                                        jg.writeStringField("name", listedObject.getName());
                                        jg.writeEndObject();
                                    }

                                    jg.writeEndArray();
                                    jg.close();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }

                            } else if (APPLICATION_XML_UTF_8.is(finalParsedAccept)) {

                                String charset = UTF_8.toString();
                                XMLStreamWriter writer = null;
                                try {
                                    writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset);

                                    writer.writeStartDocument(charset, "1.0");

                                    writer.writeStartElement("container");

                                    writer.writeAttribute("name",
                                            fromPaths(persistentContainer.getId()).containerName().get());

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        writer.writeStartElement("object");

                                        writer.writeStartElement("name");
                                        writer.writeCharacters(listedObject.getName());
                                        writer.writeEndElement();

                                        writer.writeStartElement("hash");
                                        writer.writeCharacters(
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("bytes");
                                        writer.writeCharacters(valueOf(listedObject.getLength()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("content_type");
                                        writer.writeCharacters(listedObject.getContentType());
                                        writer.writeEndElement();

                                        writer.writeStartElement("last_modified");
                                        writer.writeCharacters(
                                                toDateTimeString(listedObject.getLastModified()));
                                        writer.writeEndElement();

                                        writer.writeEndElement();
                                    }

                                    writer.writeEndElement();

                                    writer.writeEndDocument();

                                } catch (XMLStreamException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (writer != null) {
                                            writer.close();
                                        }
                                    } catch (XMLStreamException e) {
                                        LOGGER.warn(e.getLocalizedMessage(), e);
                                    }
                                }

                            } else {
                                String charset = UTF_8.toString();
                                try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                                        bufferOutputStream, charset)) {
                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {
                                        outputStreamWriter.write(listedObject.getName());
                                        outputStreamWriter.write("\n");
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            objectList.clear();
                            return bufferOutputStream;
                        }).flatMap(bufferOutputStream -> {
                            Buffer buffer = bufferOutputStream.toBuffer();
                            httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, finalParsedAccept.toString())
                                    .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
                            return AsyncIO.append(buffer, httpServerRequest.response());
                        });
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {

                }
            }

    );

}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String updateLocalization(String xml, String key, String value, String requestedLanguageId,
        String defaultLanguageId, boolean cdata, boolean localized) {

    xml = _sanitizeXML(xml);//  w ww .j a  va2s  .c o  m

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);

            if (Validator.isNull(availableLocales)) {
                availableLocales = defaultLanguageId;
            }

            if (availableLocales.indexOf(requestedLanguageId) == -1) {
                availableLocales = StringUtil.add(availableLocales, requestedLanguageId, StringPool.COMMA);
            }
        }

        UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement(_ROOT);

        if (localized) {
            xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
            xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
        }

        _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

        xmlStreamWriter.writeStartElement(key);

        if (localized) {
            xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId);
        }

        if (cdata) {
            xmlStreamWriter.writeCData(value);
        } else {
            xmlStreamWriter.writeCharacters(value);
        }

        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndDocument();

        xmlStreamWriter.close();
        xmlStreamWriter = null;

        xml = unsyncStringWriter.toString();
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

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

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

        writeBoolElement(writer, "cookiesDisabled", cookiesDisabled);
        writeStringElement(writer, "authMethod", authMethod);
        writeStringElement(writer, "authUsername", authUsername);
        writeStringElement(writer, "authPassword", authPassword);
        writeStringElement(writer, "authUsernameField", authUsernameField);
        writeStringElement(writer, "authPasswordField", authPasswordField);
        writeStringElement(writer, "authURL", authURL);
        writeStringElement(writer, "authHostname", authHostname);
        writeIntElement(writer, "authPort", authPort);
        writeStringElement(writer, "authFormCharset", authFormCharset);
        writeStringElement(writer, "authWorkstation", authWorkstation);
        writeStringElement(writer, "authDomain", authDomain);
        writeStringElement(writer, "authRealm", authRealm);
        writeStringElement(writer, "proxyHost", proxyHost);
        writeIntElement(writer, "proxyPort", proxyPort);
        writeStringElement(writer, "proxyScheme", proxyScheme);
        writeStringElement(writer, "proxyUsername", proxyUsername);
        writeStringElement(writer, "proxyPassword", proxyPassword);
        writeStringElement(writer, "proxyRealm", proxyRealm);
        writer.writeEndElement();
        writeIntElement(writer, "connectionTimeout", connectionTimeout);
        writeIntElement(writer, "socketTimeout", socketTimeout);
        writeIntElement(writer, "connectionRequestTimeout", connectionRequestTimeout);
        writeStringElement(writer, "connectionCharset", connectionCharset);
        writeBoolElement(writer, "expectContinueEnabled", expectContinueEnabled);
        writeIntElement(writer, "maxRedirects", maxRedirects);
        writeStringElement(writer, "localAddress", localAddress);
        writeBoolElement(writer, "staleConnectionCheckDisabled", staleConnectionCheckDisabled);
        writeIntElement(writer, "maxConnections", maxConnections);

        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}