Example usage for javax.xml.stream XMLOutputFactory newInstance

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

Introduction

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

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3,
            false);/*  ww w.ja  va2s.co  m*/

    writer.flush();

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = getAtomElement(propertyReader, null, null);
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = xof.createXMLEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton(
                        new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

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

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = xof.createXMLEventWriter(bos);

    propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 *
 * @param zipOutput//w  w w.  jav  a 2s.com
 * @throws XMLStreamException
 * @throws IOException
 */
private void createAndWriteManifestEntry(ZipArchiveOutputStream zipOutput)
        throws XMLStreamException, IOException {

    ZipArchiveEntry entry = new ZipArchiveEntry("manifest.xml");
    zipOutput.putArchiveEntry(entry);

    // Prepare STAX indenting writer based on a Java XMLStreamWriter that is based on the given zipped output.
    XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(zipOutput, ENCODING);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlWriter);

    int i = 1;
    writeManifestHeader(writer);
    for (SubjectDTO indicatorSubject : indicatorSubjects) {
        writeOdpAction(writer, indicatorSubject, i++);
    }
    writeManifestFooter(writer);

    zipOutput.closeArchiveEntry();
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
protected InputStream replaceLink(final InputStream toBeChanged, final String linkName,
        final InputStream replacement) throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {/*from w  w  w .  j a  v  a 2  s.  c o  m*/
        final XmlElement linkElement = getAtomElement(reader, writer, LINK,
                Collections.<Map.Entry<String, String>>singletonList(
                        new SimpleEntry<String, String>("title", linkName)));
        writer.add(linkElement.getStart());

        // ------------------------------------------
        // write inline ...
        // ------------------------------------------
        writer.add(newLine);
        writer.add(eventFactory.createStartElement("m", null, "inline"));

        addAtomElement(replacement, writer);

        writer.add(eventFactory.createEndElement("m", null, "inline"));
        writer.add(newLine);
        // ------------------------------------------

        writer.add(linkElement.getEnd());

        writer.add(reader);
        writer.flush();
        writer.close();
    } finally {
        reader.close();
        IOUtils.closeQuietly(toBeChanged);
    }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);// w  ww .jav a 2  s.c  om
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);/*from  ww w  . ja  v a 2  s  . c o m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes a single entity to the specified <code>OutputStream</code> as a complete XML
 * document.//from   w  w w.  j  a va 2s .  com
 * 
 * @param outStream
 *            The <code>OutputStream</code> to write the entity to.
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @throws XMLStreamException
 *             if an error occurs creating or accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeSingleAtomEntity(final OutputStream outStream, final TableEntity entity,
        final boolean isTableEntry, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outStream, Constants.UTF8_CHARSET);

    // default is UTF8
    xmlw.writeStartDocument(Constants.UTF8_CHARSET, "1.0");

    writeAtomEntity(entity, isTableEntry, xmlw, opContext);

    // end doc
    xmlw.writeEndDocument();
    xmlw.flush();
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes a single entity to the specified <code>OutputStream</code> as a complete XML
 * document.//from   ww  w. ja v  a2 s.  c om
 * 
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @param outStream
 *            The <code>OutputStream</code> to write the entity to.
 * 
 * @throws XMLStreamException
 *             if an error occurs creating or accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeSingleAtomEntity(final StringWriter strWriter, final TableEntity entity,
        final boolean isTableEntry, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(strWriter);

    // default is UTF8
    xmlw.writeStartDocument(Constants.UTF8_CHARSET, "1.0");

    writeAtomEntity(entity, isTableEntry, xmlw, opContext);

    // end doc
    xmlw.writeEndDocument();
    xmlw.flush();
}

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

/**
 * StAX for efficient streaming XML writing.
 * // ww  w .j  a v  a  2 s  .c om
 * @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:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * XML ??//w w w  . j av  a 2  s  . c  o  m
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeXml(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        zos.putNextEntry(entry);

        OutputStreamWriter writer = new OutputStreamWriter(zos, "UTF-8");
        XMLStreamWriter xwriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("zips");
        xwriter.writeAttribute("type", name);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);

                xwriter.writeStartElement("zip");
                xwriter.writeAttribute("zip", zip.getCode());
                xwriter.writeAttribute("x0402", zip.getX0402());
                xwriter.writeAttribute("add1", zip.getAdd1());
                xwriter.writeAttribute("add2", zip.getAdd2());
                xwriter.writeAttribute("corp", zip.getCorp());
                xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi());
                xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi());
                xwriter.writeAttribute("corpYomi", zip.getCorpYomi());
                xwriter.writeAttribute("note", zip.getNote());
                xwriter.writeEndElement();
                ++cnt;
            }
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip");
        log.info("count: " + cnt);

    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:ca.uhn.fhir.util.XmlUtil.java

static XMLOutputFactory newOutputFactory() throws FactoryConfigurationError {
    XMLOutputFactory outputFactory;
    try {//from  ww w .j ava  2s  . co  m
        outputFactory = XMLOutputFactory.newInstance();
        throwUnitTestExceptionIfConfiguredToDoSo();
    } catch (Throwable e) {
        throw new ConfigurationException("Unable to initialize StAX - XML processing is disabled", e);
    }
    return outputFactory;
}