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:Main.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory xof = XMLOutputFactory.newFactory();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);

    xsw.writeStartDocument();
    xsw.writeStartElement("response");
    xsw.writeStartElement("message");
    xsw.writeCharacters("1 < 2");
    xsw.writeEndDocument();//from w w  w  .  ja v a  2  s.c  o  m

    xsw.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory xof = XMLOutputFactory.newFactory();

    StringWriter sw = new StringWriter();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(sw);
    xsw.writeStartDocument();
    xsw.writeStartElement("foo");
    xsw.writeCharacters("<>\"&'");
    xsw.writeEndDocument();//from   w w w.jav  a  2 s.  c om

    String xml = sw.toString();
    System.out.println(xml);

    // READ THE XML
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag(); // Advance to "foo" element
    System.out.println(xsr.getElementText());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    OutputStream stream = System.out;

    XMLOutputFactory xof = XMLOutputFactory.newFactory();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(stream);

    xsw.writeStartDocument();
    xsw.writeStartElement("foo");
    xsw.writeStartElement("bar");

    xsw.writeCharacters("");
    xsw.flush();// www . jav a  2 s .  c  o m

    OutputStreamWriter osw = new OutputStreamWriter(stream);
    osw.write("<baz>Hello World<baz>");
    osw.flush();

    xsw.writeEndElement();
    xsw.writeEndElement();
    xsw.writeEndDocument();
    xsw.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
    writer.setDefaultNamespace("http://www.java2s.com");

    JAXBContext jc = JAXBContext.newInstance(WorkSet.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

    writer.writeStartDocument();
    writer.writeStartElement("http://www.java2s.com", "Import");
    writer.writeNamespace("", "http://www.java2s.com");
    writer.writeStartElement("WorkSets");

    m.marshal(new WorkSet(), writer);
    m.marshal(new WorkSet(), writer);

    writer.writeEndDocument();// ww w.java  2 s. c o  m
    writer.close();
}

From source file:fr.ritaly.dungeonmaster.item.ItemDef.java

public static void main(String[] args) throws Exception {
    final List<Item.Type> types = Arrays.asList(Item.Type.values());

    Collections.sort(types, new Comparator<Item.Type>() {
        @Override/* w w w.  j  a  v a2s .  c  om*/
        public int compare(Type o1, Type o2) {
            return o1.name().compareTo(o2.name());
        }
    });

    final StringWriter stringWriter = new StringWriter(32000);

    final XMLStreamWriter writer = new IndentingXMLStreamWriter(
            XMLOutputFactory.newFactory().createXMLStreamWriter(stringWriter));

    writer.writeStartDocument();
    writer.writeStartElement("items");
    writer.writeDefaultNamespace("yadmjc:items:1.0");

    for (Item.Type type : types) {
        writer.writeStartElement("item");
        writer.writeAttribute("id", type.name());
        writer.writeAttribute("weight", Float.toString(type.getWeight()));

        if (type.getDamage() != -1) {
            writer.writeAttribute("damage", Integer.toString(type.getDamage()));
        }

        if (type.getActivationBodyPart() != null) {
            writer.writeAttribute("activation", type.getActivationBodyPart().name());
        }

        if (type.getShield() != 0) {
            writer.writeAttribute("shield", Integer.toString(type.getShield()));
        }
        if (type.getAntiMagic() != 0) {
            writer.writeAttribute("anti-magic", Integer.toString(type.getAntiMagic()));
        }

        if (type.getDecayRate() != -1) {
            writer.writeAttribute("decay-rate", Integer.toString(type.getDecayRate()));
        }

        if (type.getDistance() != -1) {
            writer.writeAttribute("distance", Integer.toString(type.getDistance()));
        }

        if (type.getShootDamage() != -1) {
            writer.writeAttribute("shoot-damage", Integer.toString(type.getShootDamage()));
        }

        if (!type.getCarryLocations().isEmpty()) {
            writer.writeStartElement("locations");

            // Sort the locations to ensure they're always serialized in a consistent way
            for (CarryLocation location : new TreeSet<CarryLocation>(type.getCarryLocations())) {
                writer.writeEmptyElement("location");
                writer.writeAttribute("id", location.name());
            }
            writer.writeEndElement();
        }

        if (!type.getActions().isEmpty()) {
            writer.writeStartElement("actions");
            for (ActionDef actionDef : type.getActions()) {
                writer.writeEmptyElement("action");
                writer.writeAttribute("id", actionDef.getAction().name());

                if (actionDef.getMinLevel() != Champion.Level.NONE) {
                    writer.writeAttribute("min-level", actionDef.getMinLevel().name());
                }

                if (actionDef.isUseCharges()) {
                    writer.writeAttribute("use-charges", Boolean.toString(actionDef.isUseCharges()));
                }
            }
            writer.writeEndElement(); // </actions>
        }

        if (!type.getEffects().isEmpty()) {
            writer.writeStartElement("effects");
            for (Effect effect : type.getEffects()) {
                writer.writeEmptyElement("effect");
                writer.writeAttribute("stat", effect.getStatistic().name());
                writer.writeAttribute("strength", String.format("%+d", effect.getStrength()));
            }
            writer.writeEndElement(); // </effects>
        }

        writer.writeEndElement(); // </item>
    }

    writer.writeEndElement(); // </items>
    writer.writeEndDocument();

    System.out.println(stringWriter);
}

From source file:fr.ritaly.dungeonmaster.ai.CreatureDef.java

public static void main(String[] args) throws Exception {
    final List<Creature.Type> types = Arrays.asList(Creature.Type.values());

    Collections.sort(types, new Comparator<Creature.Type>() {
        @Override//  w  w w.j a v  a 2  s  .co  m
        public int compare(Creature.Type o1, Creature.Type o2) {
            return o1.name().compareTo(o2.name());
        }
    });

    final StringWriter stringWriter = new StringWriter(32000);

    final XMLStreamWriter writer = new IndentingXMLStreamWriter(
            XMLOutputFactory.newFactory().createXMLStreamWriter(stringWriter));

    writer.writeStartDocument();
    writer.writeStartElement("creatures");
    writer.writeDefaultNamespace("yadmjc:creatures:1.0");

    for (Creature.Type type : types) {
        writer.writeStartElement("creature");
        writer.writeAttribute("id", type.name());
        writer.writeAttribute("base-health", Integer.toString(type.getBaseHealth()));
        writer.writeAttribute("height", type.getHeight().name());
        writer.writeAttribute("size", type.getSize().name());
        writer.writeAttribute("awareness", Integer.toString(type.getAwareness()));
        writer.writeAttribute("bravery", Integer.toString(type.getBravery()));
        writer.writeAttribute("experience-multiplier", Integer.toString(type.getExperienceMultiplier()));
        writer.writeAttribute("move-duration", Integer.toString(type.getMoveDuration()));
        writer.writeAttribute("sight-range", Integer.toString(type.getSightRange()));
        writer.writeAttribute("absorbs-items", Boolean.toString(type.isAbsorbsItems()));
        writer.writeAttribute("levitates", Boolean.toString(type.levitates()));
        writer.writeAttribute("archenemy", Boolean.toString(type.isArchenemy()));
        writer.writeAttribute("night-vision", Boolean.toString(type.isNightVision()));
        writer.writeAttribute("sees-invisible", Boolean.toString(type.isSeesInvisible()));

        writer.writeEmptyElement("defense");
        writer.writeAttribute("anti-magic", Integer.toString(type.getAntiMagic()));
        writer.writeAttribute("armor", Integer.toString(type.getArmor()));
        writer.writeAttribute("shield", Integer.toString(type.getShield()));
        writer.writeAttribute("poison", Integer.toString(type.getPoisonResistance()));

        writer.writeEmptyElement("attack");
        writer.writeAttribute("skill", type.getAttackSkill().name());
        writer.writeAttribute("animation-duration", Integer.toString(type.getAttackAnimationDuration()));
        writer.writeAttribute("duration", Integer.toString(type.getAttackDuration()));
        writer.writeAttribute("power", Integer.toString(type.getAttackPower()));
        writer.writeAttribute("type", type.getAttackType().name());
        writer.writeAttribute("range", Integer.toString(type.getAttackRange()));
        writer.writeAttribute("probability", Integer.toString(type.getAttackProbability()));
        writer.writeAttribute("side-attack", Boolean.toString(type.isSideAttackAllowed()));

        writer.writeEmptyElement("poison");
        if (type.getPoison() != 0) {
            writer.writeAttribute("strength", Integer.toString(type.getPoison()));
        }

        if (!type.getSpells().isEmpty()) {
            writer.writeStartElement("spells");

            // Sort the spells to ensure they're always serialized in a
            // consistent way
            for (Spell.Type spell : new TreeSet<Spell.Type>(type.getSpells())) {
                writer.writeEmptyElement("spell");
                writer.writeAttribute("id", spell.name());
            }

            writer.writeEndElement(); // </spells>
        }

        if (!type.getWeaknesses().isEmpty()) {
            writer.writeStartElement("weaknesses");

            // Sort the weaknesses to ensure they're always serialized in a
            // consistent way
            for (Weakness weakness : new TreeSet<Weakness>(type.getWeaknesses())) {
                writer.writeEmptyElement("weakness");
                writer.writeAttribute("id", weakness.name());
            }

            writer.writeEndElement(); // </weaknesses>
        }

        if (!type.getDefinition().getItemDefs().isEmpty()) {
            writer.writeStartElement("items");

            for (ItemDef itemDef : type.getDefinition().getItemDefs()) {
                writer.writeEmptyElement("item");
                writer.writeAttribute("type", itemDef.type.name());
                writer.writeAttribute("min", Integer.toString(itemDef.min));
                writer.writeAttribute("max", Integer.toString(itemDef.max));

                if (itemDef.curse != null) {
                    writer.writeAttribute("curse", itemDef.curse.name());
                }
            }

            writer.writeEndElement(); // </items>
        }

        writer.writeEndElement(); // </creature>
    }

    writer.writeEndElement(); // </creatures>
    writer.writeEndDocument();

    System.out.println(stringWriter);
}

From source file:Main.java

public static XMLStreamWriter createStreamWriter() {
    if (stream != null) {
        System.out.println("ERROR: there is already an existing stream.");
    }//from  ww  w  .j a va 2s. com
    stream = new ByteArrayOutputStream();
    XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter writer = xmlFactory.createXMLStreamWriter(stream);
        writer.writeStartDocument();
        return writer;
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.norconex.jefmon.model.ConfigurationDAO.java

public static void saveConfig(JEFMonConfig config) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Saving JEF config to: " + CONFIG_FILE);
    }/*from  w ww . ja  v  a 2 s.c  o m*/

    if (!CONFIG_FILE.exists()) {
        File configDir = new File(FilenameUtils.getFullPath(CONFIG_FILE.getAbsolutePath()));
        if (!configDir.exists()) {
            LOG.debug("Creating JEF Monitor config directory for: " + CONFIG_FILE);
            configDir.mkdirs();
        }
    }

    OutputStream out = new FileOutputStream(CONFIG_FILE);
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter xml = factory.createXMLStreamWriter(out);
        xml.writeStartDocument();
        xml.writeStartElement("jefmon-config");

        xml.writeStartElement("instance-name");
        xml.writeCharacters(config.getInstanceName());
        xml.writeEndElement();

        xml.writeStartElement("default-refresh-interval");
        xml.writeCharacters(Integer.toString(config.getDefaultRefreshInterval()));
        xml.writeEndElement();

        saveRemoteUrls(xml, config.getRemoteInstanceUrls());
        saveMonitoredPaths(xml, config.getMonitoredPaths());
        saveJobActions(xml, config.getJobActions());

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

From source file:com.flexive.core.IMParser.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response//  w w  w . j a  v a 2  s .com
 * @return XML content
 * @throws XMLStreamException on errors
 * @throws IOException        on errors
 */
public static String parse(InputStream in) throws XMLStreamException, IOException {
    StringWriter sw = new StringWriter(2000);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    writer.writeStartDocument();

    int lastLevel = 0, level, lastNonValueLevel = 1;
    boolean valueEntry;
    String curr = null;
    String[] entry;
    try {
        while ((curr = br.readLine()) != null) {
            if (curr.indexOf(':') == -1 || curr.trim().length() == 0) {
                System.out.println("skipping: [" + curr + "]");
                continue; //ignore lines without ':'
            }
            level = getLevel(curr);
            curr = curr.trim();
            if (level == 0 && curr.startsWith("Image:")) {
                writer.writeStartElement("Image");
                entry = curr.split(": ");
                if (entry.length >= 2)
                    writer.writeAttribute("source", entry[1]);
                lastLevel = level;
                continue;
            }
            if (!(valueEntry = pNumeric.matcher(curr).matches())) {
                while (level < lastLevel--)
                    writer.writeEndElement();
                lastNonValueLevel = level;
            } else
                level = lastNonValueLevel + 1;
            if (curr.endsWith(":")) {
                writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(cleanElement(entry[0]));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", cleanElement(entry[0]));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        System.err.println("Error at [" + curr + "]:" + e.getMessage());
        e.printStackTrace();
    }

    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *//*  ww w  .j av  a 2  s .  c o  m*/
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}