Example usage for javax.xml.stream XMLStreamWriter setDefaultNamespace

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

Introduction

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

Prototype

public void setDefaultNamespace(String uri) throws XMLStreamException;

Source Link

Document

Binds a URI to the default namespace This URI is bound in the scope of the current START_ELEMENT / END_ELEMENT pair.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
    writer.setDefaultNamespace("http://www.example.com/ns1");
    writer.writeStartElement("http://www.example.com/ns1", "sample");
    writer.writeDefaultNamespace("http://www.example.com/ns1");
    writer.writeEmptyElement("inner");
    writer.setDefaultNamespace("http://www.example.com/ns2");
    writer.writeStartElement("http://www.example.com/ns2", "inner2");
    writer.writeDefaultNamespace("http://www.example.com/ns2");
    writer.writeNamespace("ns1", "http://www.example.com/ns1");
    writer.writeEmptyElement("http://www.example.com/ns1", "inner");

    writer.writeEndDocument();/* w  w  w.  j av  a2  s. com*/
    writer.flush();
}

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();/*from  w w w . j a va 2s .c o m*/
    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();
    writer.close();
}

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

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *///from  w  ww.j  av  a  2  s.  c  om
@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();
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private XMLStreamWriter makeXMLSerializer(OutputStream out) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    try {/*  www  . j  a  v  a2  s.c  o  m*/
        XMLStreamWriter serializer = factory.createXMLStreamWriter(out, "UTF-8");

        serializer.setDefaultNamespace("http://marklogic.com/appservices/search");
        serializer.setPrefix("xs", XMLConstants.W3C_XML_SCHEMA_NS_URI);

        return serializer;
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

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

/**
 * Generates a XML response that describe the EC2 instances
 *///from ww w . j  a v a  2s .c o  m
private byte[] generateDescribeInstancesResponse() {
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final 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");
            {
                if (Files.exists(nodes)) {
                    for (String address : Files.readAllLines(nodes)) {

                        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(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("dnsName");
                                    sw.writeCharacters(address);
                                    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(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("ipAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                        sw.writeEndElement();
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return out.toString().getBytes(UTF_8);
}

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

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {/*from  w  w w  .j a v 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:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private void sparqlQuery(String sparql, TripleStore ts, Map<String, String[]> params, String pathInfo,
        HttpServletResponse res) throws Exception {
    if (sparql == null) {
        Map err = error(SC_BAD_REQUEST, "No query specified.", null);
        output(err, params, pathInfo, res);
        return;//from  ww w  . j av a2s  . c o m
    } else {
        log.info("sparql: " + sparql);
    }

    // sparql query
    BindingIterator objs = ts.sparqlSelect(sparql);

    // start output
    String sparqlNS = "http://www.w3.org/2005/sparql-results#";
    res.setContentType("application/sparql-results+xml");
    OutputStream out = res.getOutputStream();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter stream = factory.createXMLStreamWriter(out);
    stream.setDefaultNamespace(sparqlNS);
    stream.writeStartDocument();
    stream.writeStartElement("sparql");

    // output bindings
    boolean headerWritten = false;
    while (objs.hasNext()) {
        Map<String, String> binding = objs.nextBinding();

        // write header on first binding
        if (!headerWritten) {
            Iterator<String> it = binding.keySet().iterator();
            stream.writeStartElement("head");
            while (it.hasNext()) {
                String k = it.next();
                stream.writeStartElement("variable");
                stream.writeAttribute("name", k);
                stream.writeEndElement();
            }
            stream.writeEndElement();
            stream.writeStartElement("results"); // ordered='false' distinct='false'
            headerWritten = true;
        }

        stream.writeStartElement("result");
        Iterator<String> it = binding.keySet().iterator();
        while (it.hasNext()) {
            String k = it.next();
            String v = binding.get(k);
            stream.writeStartElement("binding");
            stream.writeAttribute("name", k);
            String type = null;
            if (v.startsWith("\"") && v.endsWith("\"")) {
                type = "literal";
                v = v.substring(1, v.length() - 1);
            } else if (v.startsWith("_:")) {
                type = "bnode";
                v = v.substring(2);
            } else {
                type = "uri";
            }
            stream.writeStartElement(type);
            stream.writeCharacters(v);
            stream.writeEndElement();
            stream.writeEndElement();
        }
        stream.writeEndElement();
    }

    // finish output
    stream.writeEndElement();
    stream.writeEndDocument();
    stream.flush();
    stream.close();
}

From source file:org.activiti.bpmn.converter.export.DefinitionsRootExport.java

@SuppressWarnings("unchecked")
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
    xtw.writeStartDocument(encoding, "1.0");

    // start definitions root element
    xtw.writeStartElement(ELEMENT_DEFINITIONS);
    xtw.setDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
    xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE);
    xtw.writeNamespace(ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE);
    xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE);
    xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
    xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
    for (String prefix : model.getNamespaces().keySet()) {
        if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix))
            xtw.writeNamespace(prefix, model.getNamespaces().get(prefix));
    }/*  www .  j  a  va  2s  .c o m*/
    xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE);
    xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
    if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace());
    } else {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE);
    }

    BpmnXMLUtil.writeCustomAttributes(model.getDefinitionsAttributes().values(), xtw, model.getNamespaces(),
            defaultAttributes);
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * Method serializeNamespace./*from www  .  j a v  a 2 s .  c o m*/
 *
 * @param namespace
 * @param writer
 * @throws XMLStreamException
 * @deprecated Use serializeStartpart instead
 */
public static void serializeNamespace(OMNamespace namespace, XMLStreamWriter writer) throws XMLStreamException {
    if (namespace == null) {
        return;
    }
    String uri = namespace.getNamespaceURI();
    String prefix = namespace.getPrefix();

    if (uri != null && !"".equals(uri)) {
        String prefixFromWriter = writer.getPrefix(uri);

        // Handling Default Namespaces First
        // Case 1 :
        //        here we are trying define a default namespace. But has this been defined in the current context.
        //        yes, there can be a default namespace, but it may have a different URI. If its a different URI
        //        then explicitly define the default namespace here.
        // Case 2 :
        //        The passed in namespace is a default ns, but there is a non-default ns declared
        //        in the current scope.
        if (("".equals(prefix) && "".equals(prefixFromWriter)
                && !uri.equals(writer.getNamespaceContext().getNamespaceURI("")))
                || (prefix != null && "".equals(prefix)
                        && (prefixFromWriter == null || !prefix.equals(prefixFromWriter)))) {
            // this has not been declared earlier
            writer.writeDefaultNamespace(uri);
            writer.setDefaultNamespace(uri);
        } else {
            prefix = prefix == null ? getNextNSPrefix(writer) : prefix;
            if (prefix != null && !prefix.equals(prefixFromWriter)
                    && !checkForPrefixInTheCurrentContext(writer, uri, prefix)) {
                writer.writeNamespace(prefix, uri);
                writer.setPrefix(prefix, uri);
            }
        }
    } else {
        // now the nsURI passed is "" or null. Meaning we gonna work with defaultNS.
        // check whether there is a defaultNS already declared. If yes, is it the same as this ?
        String currentDefaultNSURI = writer.getNamespaceContext().getNamespaceURI("");
        if ((currentDefaultNSURI != null && !currentDefaultNSURI.equals(uri))
                || uri != null && !uri.equals(currentDefaultNSURI)) {
            // this has not been declared earlier
            writer.writeDefaultNamespace(uri);
            writer.setDefaultNamespace(uri);
        }
    }
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * Generate setPrefix/setDefaultNamespace if the prefix is not associated
 *
 * @param prefix/*from ww w.  j ava  2  s  . c o  m*/
 * @param namespace
 * @param writer
 * @param attr
 * @return prefix name if a setPrefix/setDefaultNamespace is performed
 */
public static String generateSetPrefix(String prefix, String namespace, XMLStreamWriter writer, boolean attr)
        throws XMLStreamException {
    prefix = (prefix == null) ? "" : prefix;

    // If the prefix and namespace are already associated, no generation is needed
    if (isAssociated(prefix, namespace, writer)) {
        return null;
    }

    // Attributes without a prefix always are associated with the unqualified namespace
    // according to the schema specification.  No generation is needed.
    if (prefix.length() == 0 && namespace == null && attr) {
        return null;
    }

    // Generate setPrefix/setDefaultNamespace if the prefix is not associated.
    String newPrefix = null;
    if (namespace != null) {
        // Qualified Namespace
        if (prefix.length() == 0) {
            writer.setDefaultNamespace(namespace);
            newPrefix = "";
        } else {
            writer.setPrefix(prefix, namespace);
            newPrefix = prefix;
        }
    } else {
        // Unqualified Namespace
        // Disable the default namespace
        writer.setDefaultNamespace("");
        newPrefix = "";
    }
    return newPrefix;
}