Example usage for javax.xml.stream XMLStreamWriter writeStartDocument

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

Introduction

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

Prototype

public void writeStartDocument() throws XMLStreamException;

Source Link

Document

Write the XML Declaration.

Usage

From source file:org.osaf.cosmo.mc.MorseCodeServlet.java

private void handleGeneralException(MorseCodeException e, HttpServletResponse resp) throws IOException {
    if (e.getCode() >= 500)
        log.error("Unknown Morse Code exception", e);
    else if (e.getCode() >= 400)
        log.info("Client error (" + e.getCode() + "): " + e.getMessage());

    resp.setStatus(e.getCode());//from   ww  w .j a  v a 2 s  .c o m
    if (!e.hasContent())
        return;

    XMLStreamWriter writer = null;

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        e.writeTo(writer);
        writer.writeEndDocument();

        resp.setContentType("application/xml");
        byte[] bytes = out.toByteArray();
        resp.setContentLength(bytes.length);
        resp.getOutputStream().write(bytes);
    } catch (Throwable e2) {
        log.error("Error writing XML", e2);
        log.error("Original exception", e);
        resp.setStatus(500);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e2) {
                log.warn("Unable to close XML writer", e2);
            }
        }
    }
}

From source file:org.rhq.enterprise.server.sync.ExportingInputStream.java

/**
 * @param wrt/*from www.j  a va2 s.c  om*/
 * @throws XMLStreamException 
 */
private void exportPrologue(XMLStreamWriter wrt) throws XMLStreamException {
    wrt.setDefaultNamespace(SynchronizationConstants.EXPORT_NAMESPACE);
    wrt.setPrefix(SynchronizationConstants.EXPORT_NAMESPACE_PREFIX, SynchronizationConstants.EXPORT_NAMESPACE);
    wrt.setPrefix(SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE_PREFIX,
            SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE);
    wrt.setPrefix(SynchronizationConstants.CONFIGURATION_NAMESPACE_PREFIX,
            SynchronizationConstants.CONFIGURATION_NAMESPACE);

    NamespaceContext nsContext = SynchronizationConstants.createConfigurationExportNamespaceContext();

    wrt.setNamespaceContext(nsContext);

    wrt.writeStartDocument();
    wrt.writeStartElement(SynchronizationConstants.EXPORT_NAMESPACE,
            SynchronizationConstants.CONFIGURATION_EXPORT_ELEMENT);
    wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE_PREFIX,
            ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE);
    wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_NAMESPACE_PREFIX,
            SynchronizationConstants.CONFIGURATION_NAMESPACE);

    writeValidators(wrt);
}

From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java

public void testCanExportAndImportState() throws Exception {
    final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class);

    final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager);

    context.checking(new Expectations() {
        {//from w w  w.  j a v a 2s. com
            oneOf(pluginManager).getInstalledPlugins();
            will(returnValue(new ArrayList<Plugin>(getDeployedPlugins())));
        }
    });

    validator.initialize(null, null);

    StringWriter output = new StringWriter();
    try {
        XMLOutputFactory ofactory = XMLOutputFactory.newInstance();

        XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output);
        //wrap the exported plugins in "something" so that we produce
        //a valid xml
        wrt.writeStartDocument();
        wrt.writeStartElement("root");

        validator.exportState(new ExportWriter(wrt));

        wrt.writeEndDocument();

        wrt.close();

        StringReader input = new StringReader(output.toString());

        try {
            XMLInputFactory ifactory = XMLInputFactory.newInstance();
            XMLStreamReader rdr = ifactory.createXMLStreamReader(input);

            //push the reader to the start of the plugin elements
            //this is what is expected by the validators
            rdr.nextTag();

            validator.initializeExportedStateValidation(new ExportReader(rdr));

            rdr.close();

            assertEquals(validator.getPluginsToValidate(), getDeployedPlugins());
        } finally {
            input.close();
        }
    } catch (Exception e) {
        LOG.error("Test failed. Output generated so far:\n" + output, e);
        throw e;
    } finally {
        output.close();
    }
}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;//from w  ww .  ja v  a 2s  .  co  m
    XMLStreamReader rdr = null;

    OutputStream out = null;
    XMLStreamWriter outWrt = null;

    try {
        Set<String> processedPropertyNames = new HashSet<String>();

        in = new BufferedInputStream(new FileInputStream(configFile));
        rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);

        File tmpFile = File.createTempFile("hadoop-plugin", null);
        out = new FileOutputStream(tmpFile);
        outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);

        ByteArrayOutputStream stash = new ByteArrayOutputStream();
        XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash);
        boolean outputActive = true;

        outWrt.writeStartDocument();

        while (rdr.hasNext()) {
            int event = rdr.next();

            XMLStreamWriter wrt = outputActive ? outWrt : stashWrt;

            switch (event) {
            case XMLStreamConstants.ATTRIBUTE:
                break;
            case XMLStreamConstants.CDATA:
                wrt.writeCData(rdr.getText());
                break;
            case XMLStreamConstants.CHARACTERS:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.COMMENT:
                wrt.writeComment(rdr.getText());
                break;
            case XMLStreamConstants.DTD:
                wrt.writeDTD(rdr.getText());
                break;
            case XMLStreamConstants.END_DOCUMENT:
                wrt.writeEndDocument();
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    String encoding = rdr.getEncoding();
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }

                    String propertyTagSoFar = Charset.forName(encoding)
                            .decode(ByteBuffer.wrap(stash.toByteArray())).toString();
                    DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps);

                    //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write.
                    outWrt.flush();
                    out.write(propAndTag.updatedTag.getBytes("UTF-8"));

                    processedPropertyNames.add(propAndTag.propertyName);

                    //reset stuff
                    stash.reset();
                    wrt = outWrt;
                    outputActive = true;
                } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    //now add the new props
                    for (String prop : processedPropertyNames) {
                        allProps.remove(prop);
                    }

                    for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) {
                        outWrt.writeStartElement(PROPERTY_TAG_NAME);

                        outWrt.writeStartElement(NAME_TAG_NAME);
                        outWrt.writeCharacters(e.getKey());
                        outWrt.writeEndElement();

                        outWrt.writeStartElement(VALUE_TAG_NAME);
                        outWrt.writeCharacters(e.getValue().getStringValue());
                        outWrt.writeEndElement();

                        outWrt.writeEndElement();
                    }
                }
                wrt.writeEndElement();
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                wrt.writeEntityRef(rdr.getText());
                break;
            case XMLStreamConstants.NAMESPACE:
                for (int i = 0; i < rdr.getNamespaceCount(); ++i) {
                    wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i));
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData());
                break;
            case XMLStreamConstants.SPACE:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.START_DOCUMENT:
                //this seems to be never called for some strange reason
                //wrt.writeStartDocument();
                break;
            case XMLStreamConstants.START_ELEMENT:
                wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(),
                        rdr.getName().getNamespaceURI());

                for (int i = 0; i < rdr.getAttributeCount(); ++i) {
                    wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i),
                            rdr.getAttributeLocalName(i), rdr.getAttributeValue(i));
                }

                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    wrt.writeCharacters("");
                    outputActive = false;
                }
                break;
            }
        }

        outWrt.flush();
        out.flush();
        out.close();

        in.close();

        //now copy the temp file in the place of the original one
        FileUtil.copyFile(tmpFile, configFile);
    } finally {
        rdr.close();

        outWrt.flush();
        outWrt.close();

        try {
            in.close();
        } finally {
            out.flush();
            out.close();
        }
    }
}

From source file:org.unitedinternet.cosmo.dav.impl.StandardDavResponse.java

public void sendDavError(CosmoDavException e) throws IOException {
    setStatus(e.getErrorCode());//from ww w. j a  v a  2  s  .  c om
    if (!e.hasContent()) {
        return;
    }

    XMLStreamWriter writer = null;

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        e.writeTo(writer);
        writer.writeEndDocument();

        setContentType("text/xml; charset=UTF-8");
        byte[] bytes = out.toByteArray();
        setContentLength(bytes.length);
        getOutputStream().write(bytes);
    } catch (Exception e2) {
        LOG.error("Error writing XML", e2);
        LOG.error("Original exception", e);
        setStatus(500);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e2) {
                LOG.warn("Unable to close XML writer", e2);
            }
        }
    }
}

From source file:org.vanbest.xmltv.Horizon.java

/**
 * @param args//from w w w. j av  a  2s.c om
 */
public static void main(String[] args) {
    Config config = Config.getDefaultConfig();
    Horizon horizon = new Horizon(config);
    horizon.clearCache();
    try {
        List<Channel> channels = horizon.getChannels();
        System.out.println("Channels: " + channels);
        XMLStreamWriter writer = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new FileWriter("horizon.xml"));
        writer.writeStartDocument();
        writer.writeCharacters("\n");
        writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
        writer.writeCharacters("\n");
        writer.writeStartElement("tv");
        // List<Channel> my_channels = channels;
        List<Channel> my_channels = channels.subList(0, 5);
        for (Channel c : my_channels) {
            c.serialize(writer, true);
        }
        writer.flush();
        for (int day = 0; day < 5; day++) {
            List<Programme> programmes = horizon.getProgrammes(my_channels, day);
            for (Programme p : programmes) {
                p.serialize(writer);
            }
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        if (!config.quiet) {
            EPGSource.Stats stats = horizon.getStats();
            System.out.println("Number of programmes from cache: " + stats.cacheHits);
            System.out.println("Number of programmes fetched: " + stats.cacheMisses);
            System.out.println("Number of fetch errors: " + stats.fetchErrors);
        }
        horizon.close();
    } catch (Exception e) {
        logger.error("Error in horizon testing", e);
    }
}

From source file:org.vanbest.xmltv.Main.java

public void fetchData() throws FactoryConfigurationError, Exception {
    if (!config.quiet) {
        showHeader();// ww w  . j av a 2s  .c o  m
        logger.info("Fetching programme data for " + this.days + " days starting from day " + this.offset);
        int enabledCount = 0;
        for (Channel c : config.channels) {
            if (c.enabled)
                enabledCount++;
        }
        logger.info("... from " + enabledCount + " channels");
        logger.info("... using cache at " + config.cacheDbHandle);
    }
    if (clearCache) {
        ProgrammeCache cache = new ProgrammeCache(config);
        cache.clear();
        cache.close();
    }
    Map<String, EPGSource> guides = new HashMap<String, EPGSource>();
    EPGSourceFactory factory = EPGSourceFactory.newInstance();
    // EPGSource gids = new TvGids(config);
    // if (clearCache) gids.clearCache();

    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(outputWriter);
    writer.writeStartDocument();
    writer.writeCharacters("\n");
    writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
    writer.writeCharacters("\n");
    writer.writeStartElement("tv");
    writer.writeAttribute("generator-info-url", "http://github.com/janpascal/tv_grab_nl_java");
    writer.writeAttribute("source-info-url", "http://tvgids.nl/");
    writer.writeAttribute("source-info-name", "TvGids.nl");
    writer.writeAttribute("generator-info-name",
            "tv_grab_nl_java release " + config.project_version + ", built " + config.build_time);
    writer.writeCharacters(System.getProperty("line.separator"));

    for (Channel c : config.channels)
        if (c.enabled)
            c.serialize(writer, config.fetchLogos);

    for (int day = offset; day < offset + days; day++) {
        if (!config.quiet)
            System.out.print("Fetching information for day " + day);
        for (Channel c : config.channels) {
            if (!c.enabled)
                continue;
            if (!config.quiet)
                System.out.print(".");
            if (!guides.containsKey(c.source)) {
                guides.put(c.source, factory.createEPGSource(c.source, config));
            }
            List<Programme> programmes = guides.get(c.source).getProgrammes(c, day);
            for (Programme p : programmes)
                p.serialize(writer);
            writer.flush();
        }
        if (!config.quiet)
            System.out.println();
    }

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

    for (String source : guides.keySet()) {
        guides.get(source).close();
    }

    if (!config.quiet) {
        EPGSource.Stats stats = new EPGSource.Stats();
        for (String source : guides.keySet()) {
            EPGSource.Stats part = guides.get(source).getStats();
            stats.cacheHits += part.cacheHits;
            stats.cacheMisses += part.cacheMisses;
            stats.fetchErrors += part.fetchErrors;
        }
        logger.info("Number of programmes from cache: " + stats.cacheHits);
        logger.info("Number of programmes fetched: " + stats.cacheMisses);
        logger.warn("Number of fetch errors: " + stats.fetchErrors);
    }
}

From source file:org.vanbest.xmltv.RTL.java

/**
 * @param args// w w w . j  a v a2 s  .  c o  m
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws FileNotFoundException {
    debug = true;
    Logger.getRootLogger().setLevel(Level.TRACE);

    Config config = Config.getDefaultConfig();
    config.niceMilliseconds = 50;
    RTL rtl = new RTL(config);
    if (debug) {
        rtl.cache.clear();
        logger.info("Writing CSV to rtl.csv");
        rtl.debugWriter = new PrintWriter(new BufferedOutputStream(new FileOutputStream("rtl.csv")));
        rtl.debugWriter.print("\"zender\",\"starttime\",\"title\",\"quark1\",\"quark2\",");
        /*
        for (int k = 0; k < rtl.xmlKeys.length; k++) {
                rtl.debugWriter.print(rtl.xmlKeys[k]);
                rtl.debugWriter.print(",");
        }
        */
        rtl.debugWriter.println();
    }

    try {
        List<Channel> channels = rtl.getChannels();
        logger.info("Channels: " + channels);
        XMLStreamWriter writer = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new FileWriter("rtl.xml"));
        writer.writeStartDocument();
        writer.writeCharacters("\n");
        writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
        writer.writeCharacters("\n");
        writer.writeStartElement("tv");
        for (Channel c : channels) {
            c.serialize(writer, true);
        }
        writer.flush();
        // List<Programme> programmes =
        // rtl.getProgrammes(channels.subList(6, 9), 0);
        for (int day = 0; day < 10; day++) {
            List<Programme> programmes = rtl.getProgrammes(channels, day);
            for (Programme p : programmes) {
                p.serialize(writer);
            }
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        if (!config.quiet) {
            EPGSource.Stats stats = rtl.getStats();
            logger.info("Number of programmes from cache: " + stats.cacheHits);
            logger.info("Number of programmes fetched: " + stats.cacheMisses);
            logger.info("Number of fetch errors: " + stats.fetchErrors);
        }
        if (debug) {
            rtl.debugWriter.flush();
            rtl.debugWriter.close();
        }
        rtl.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        logger.debug("Exception in RTL.main()", e);
    }
}

From source file:org.vanbest.xmltv.TvGids.java

/**
 * @param args//from ww w.j a va2 s.  co m
 */
public static void main(String[] args) {
    Config config = Config.getDefaultConfig();
    TvGids gids = new TvGids(config);
    try {
        List<Channel> channels = gids.getChannels();
        System.out.println("Channels: " + channels);
        XMLStreamWriter writer = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new FileWriter("tvgids.xml"));
        writer.writeStartDocument();
        writer.writeCharacters("\n");
        writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
        writer.writeCharacters("\n");
        writer.writeStartElement("tv");
        // List<Channel> my_channels = channels;
        List<Channel> my_channels = channels.subList(0, 15);
        for (Channel c : my_channels) {
            c.serialize(writer, true);
        }
        writer.flush();
        List<Programme> programmes = gids.getProgrammes(my_channels, 2);
        for (Programme p : programmes) {
            p.serialize(writer);
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        if (!config.quiet) {
            EPGSource.Stats stats = gids.getStats();
            System.out.println("Number of programmes from cache: " + stats.cacheHits);
            System.out.println("Number of programmes fetched: " + stats.cacheMisses);
            System.out.println("Number of fetch errors: " + stats.fetchErrors);
        }
        gids.close();
    } catch (Exception e) {
        logger.error("Error in tvgids testing", e);
    }
}

From source file:org.vanbest.xmltv.ZiggoGids.java

/**
 * @param args//from   w w w.j  av a2  s  .co m
 */
public static void main(String[] args) {
    Config config = Config.getDefaultConfig();
    logger.setLevel(Level.TRACE);
    ZiggoGids gids = new ZiggoGids(config);
    try {
        List<Channel> channels = gids.getChannels();
        System.out.println("Channels: " + channels);

        XMLStreamWriter writer = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new FileWriter("ziggogids.xml"));
        writer.writeStartDocument();
        writer.writeCharacters("\n");
        writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
        writer.writeCharacters("\n");
        writer.writeStartElement("tv");
        //List<Channel> my_channels = channels;
        //List<Channel> my_channels = channels.subList(0, 15);
        List<Channel> my_channels = channels.subList(0, 4);
        for (Channel c : my_channels) {
            c.serialize(writer, true);
        }
        writer.flush();
        List<Programme> programmes = gids.getProgrammes(my_channels, 2);
        for (Programme p : programmes) {
            p.serialize(writer);
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        if (!config.quiet) {
            EPGSource.Stats stats = gids.getStats();
            System.out.println("Number of programmes from cache: " + stats.cacheHits);
            System.out.println("Number of programmes fetched: " + stats.cacheMisses);
            System.out.println("Number of fetch errors: " + stats.fetchErrors);
        }

        gids.close();
    } catch (Exception e) {
        logger.error("Error in ziggogids testing", e);
    }
}