Example usage for javax.xml.stream XMLOutputFactory createXMLStreamWriter

List of usage examples for javax.xml.stream XMLOutputFactory createXMLStreamWriter

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory createXMLStreamWriter.

Prototype

public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamWriter that writes to a JAXP result.

Usage

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  .  j  ava2  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: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);/*from w w  w .j a  va  2s. 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:msearch.filmlisten.MSFilmlisteSchreiben.java

private void xmlSchreibenStart(String datei) throws IOException, XMLStreamException {
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(947623049, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*from w w w.j  a  va 2  s. co m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    if (datei.endsWith(MSConst.FORMAT_BZ2)) {
        bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                9 /*Blocksize: 1 - 9*/);
        out = new OutputStreamWriter(bZip2CompressorOutputStream, MSConst.KODIERUNG_UTF);
    } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
        zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
        ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
        zipOutputStream.putNextEntry(entry);
        out = new OutputStreamWriter(zipOutputStream, MSConst.KODIERUNG_UTF);
    } else {
        out = new OutputStreamWriter(new FileOutputStream(file), MSConst.KODIERUNG_UTF);
    }
    writer = outFactory.createXMLStreamWriter(out);
    writer.writeStartDocument("UTF-8", "1.0");
    writer.writeCharacters("\n");//neue Zeile
    writer.writeStartElement(MSConst.XML_START);
    writer.writeCharacters("\n");//neue Zeile
}

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

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//  w  w w  .  j  a  v a 2s. c  om
        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);
    }
}

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

public void toXMLString(OutputStream _out, boolean writeCDataSections) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    try {/*from  w w  w. java  2s  .c o  m*/
        XMLStreamWriter writer = outputFactory.createXMLStreamWriter(_out);
        toJXMLString(writer, writeCDataSections);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    }
}

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

public void toXMLString(Writer _writer) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    try {/*  w w  w. j  ava 2s .  c o  m*/
        XMLStreamWriter writer = outputFactory.createXMLStreamWriter(_writer);
        toJXMLString(writer);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    }

}

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

/**
 * Writes this object to the specified output stream
 * @param _out output stream/* ww  w.j a  v  a  2  s  .c o  m*/
 * @throws FioranoException FioranoException
 */
public void toXMLString(OutputStream _out) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    try {
        XMLStreamWriter writer = outputFactory.createXMLStreamWriter(_out);
        toJXMLString(writer);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    }

}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, XMLStreamWriter)} method when jaxbElement is null. </p> {@link
 * IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *//*from   ww w.ja va 2 s . co  m*/
@Test(expected = IllegalArgumentException.class)
public void testMarshallXMLStreamWriterNull1() throws Exception {

    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    marshaller.marshal(null, outputFactory.createXMLStreamWriter(writer));
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link XMLStreamWriter}.
 *
 * @param entity the object to marshall//  w  w w.  ja v  a2s  . com
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallXMLStreamWriter(Object entity) throws Exception {
    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(writer);
    marshaller.marshal(entity, xmlStreamWriter);

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

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

/**
 * Writes manageable properties file with the specified label
 * @param applicationFolderName event process folder
 * @param label environment label/*from w w w.j av  a 2  s .c o  m*/
 * @throws FioranoException FioranoException
 * @throws XMLStreamException XMLStreamException
 */
public void writeManageableProperties(File applicationFolderName, Label label)
        throws FioranoException, XMLStreamException {
    File manageablePropertiesFile = getManageablePropertiesFile(applicationFolderName, label);
    if (!manageablePropertiesFile.exists())
        manageablePropertiesFile.getParentFile().mkdirs();

    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //        System.out.println(".....:"+outputFactory);
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    XMLStreamWriter writer = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(manageablePropertiesFile);
        writer = outputFactory.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        {

            writer.writeStartElement(ELEM_TARGET, ELEM_TARGET, Namespaces.URI_TARGET);
            writer.writeAttribute(XMLNS_TARGET, Namespaces.URI_TARGET);
            writer.writeAttribute(XMLNS_XSI, Namespaces.URI_XSI);
            writer.writeAttribute(XSI_LOCATION, Namespaces.URI_ENV_XSD);
            {
                for (ServiceInstance instance : getServiceInstances()) {
                    instance.writeManageableProperties(writer);
                }

            }
            writer.writeEndElement();
        }

        writer.writeEndDocument();

        writer.flush();
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (XMLStreamException e) {
            // Ignore
        }

        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            // Ignore
        }
    }

}