Example usage for javax.xml.stream XMLStreamWriter writeStartElement

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

Introduction

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

Prototype

public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException;

Source Link

Document

Writes a start tag to the output

Usage

From source file:org.deegree.services.sos.SOSController.java

private void doGetFeatureOfInterest(GetFeatureOfInterest foi, HttpResponseBuffer response)
        throws IOException, XMLStreamException {
    XMLStreamWriter xmlWriter = response.getXMLWriter();

    List<String> foiIDs = Arrays.asList(foi.getFoiID());

    xmlWriter.writeStartElement(SA_PREFIX, "SamplingFeatureCollection", SA_NS);
    xmlWriter.writeNamespace(SA_PREFIX, SA_NS);
    xmlWriter.writeNamespace(XSI_PREFIX, XSINS);
    xmlWriter.writeNamespace(XLINK_PREFIX, XLNNS);
    xmlWriter.writeNamespace(GML_PREFIX, GMLNS);

    xmlWriter.writeAttribute(XSI_PREFIX, XSINS, "schemaLocation",
            "http://www.opengis.net/sampling/1.0 http://schemas.opengis.net/sampling/1.0.0/sampling.xsd");

    // TODO a url should be specified in the xlink:href of sampledFeature
    xmlWriter.writeEmptyElement(SA_PREFIX, "sampledFeature", SA_NS);

    for (Offering offering : sosService.getAllOfferings()) {
        for (Procedure procedure : offering.getProcedures()) {
            if (foiIDs.contains(procedure.getFeatureOfInterestHref())) {
                Geometry procGeometry = procedure.getLocation();
                if (procGeometry instanceof Point) { // TODO check if the procedure can have some other geometries
                    // and if so,
                    // handle them

                    xmlWriter.writeStartElement(SA_PREFIX, "member", SA_NS);

                    xmlWriter.writeStartElement(SA_PREFIX, "SamplingPoint", SA_NS);
                    xmlWriter.writeStartElement(GML_PREFIX, "name", GMLNS);
                    xmlWriter.writeCharacters(procedure.getFeatureOfInterestHref());
                    // TODO if the GetFeatureOfInterest does not provide a foi but a location instead, search
                    // for all
                    // sensors
                    // inside that BBOX
                    xmlWriter.writeEndElement();

                    // TODO a url should be specified in the xlink:href of sampledFeature
                    xmlWriter.writeEmptyElement(SA_PREFIX, "sampledFeature", SA_NS);

                    xmlWriter.writeStartElement(SA_PREFIX, "position", SA_NS);
                    // exporting a gml:Point TODO use GML encoder
                    xmlWriter.writeStartElement(GML_PREFIX, "Point", GMLNS);
                    // have the last part of the foiID as the Point id attribute
                    String[] foiParts = procedure.getFeatureOfInterestHref().split(":");
                    xmlWriter.writeAttribute(GML_PREFIX, GMLNS, "id", foiParts[foiParts.length - 1]);

                    xmlWriter.writeStartElement(GML_PREFIX, "pos", GMLNS);
                    ICRS foiCRS = null;/*from   ww w .  jav a 2  s  .  com*/
                    foiCRS = procGeometry.getCoordinateSystem();
                    xmlWriter.writeAttribute("srsName", foiCRS.getCode().toString());

                    Point p = (Point) procGeometry;
                    xmlWriter.writeCharacters(p.get0() + " " + p.get1());
                    xmlWriter.writeEndElement(); // gml:pos
                    xmlWriter.writeEndElement(); // gml:Point
                    xmlWriter.writeEndElement(); // gml:position
                    xmlWriter.writeEndElement(); // sa:SamplingPoint
                    xmlWriter.writeEndElement(); // sa:member
                }
            }
        }
    }

    xmlWriter.writeEndElement(); // sa:SamplingFeatureCollection
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
}

From source file:org.deegree.services.wfs.WebFeatureService.java

@Override
public void doSOAP(SOAPEnvelope soapDoc, HttpServletRequest request, HttpResponseBuffer response,
        List<FileItem> multiParts, SOAPFactory factory)
        throws ServletException, IOException, org.deegree.services.authentication.SecurityException {
    LOG.debug("doSOAP");

    if (disableBuffering) {
        super.doSOAP(soapDoc, request, response, multiParts, factory);
        return;// www  .j  a v a2 s.  co  m
    }

    Version requestVersion = null;
    try {
        if (soapDoc.getVersion() instanceof SOAP11Version) {
            response.setContentType("application/soap+xml");
            XMLStreamWriter xmlWriter = response.getXMLWriter();
            String soapEnvNS = "http://schemas.xmlsoap.org/soap/envelope/";
            String xsiNS = "http://www.w3.org/2001/XMLSchema-instance";
            xmlWriter.writeStartElement("soap", "Envelope", soapEnvNS);
            xmlWriter.writeNamespace("soap", soapEnvNS);
            xmlWriter.writeNamespace("xsi", xsiNS);
            xmlWriter.writeAttribute(xsiNS, "schemaLocation",
                    "http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/");
            xmlWriter.writeStartElement(soapEnvNS, "Body");
        } else {
            beginSOAPResponse(response);
        }

        OMElement body = soapDoc.getBody().getFirstElement().cloneOMElement();
        XMLStreamReader bodyXmlStream = body.getXMLStreamReaderWithoutCaching();

        String requestName = body.getLocalName();
        WFSRequestType requestType = getRequestTypeByName(requestName);

        // check if requested version is supported and offered (except for GetCapabilities)
        requestVersion = getVersion(body.getAttributeValue(new QName("version")));
        if (requestType != WFSRequestType.GetCapabilities) {
            requestVersion = checkVersion(requestVersion);

            // needed for CITE 1.1.0 compliance
            String serviceAttr = body.getAttributeValue(new QName("service"));
            if (serviceAttr != null && !("WFS".equals(serviceAttr) || "".equals(serviceAttr))) {
                throw new OWSException("Wrong service attribute: '" + serviceAttr + "' -- must be 'WFS'.",
                        INVALID_PARAMETER_VALUE, "service");
            }
        }

        switch (requestType) {
        case CreateStoredQuery:
            CreateStoredQueryXMLAdapter createStoredQueryAdapter = new CreateStoredQueryXMLAdapter();
            createStoredQueryAdapter.setRootElement(body);
            CreateStoredQuery createStoredQuery = createStoredQueryAdapter.parse();
            storedQueryHandler.doCreateStoredQuery(createStoredQuery, response);
            break;
        case DescribeFeatureType:
            DescribeFeatureTypeXMLAdapter describeFtAdapter = new DescribeFeatureTypeXMLAdapter();
            describeFtAdapter.setRootElement(body);
            DescribeFeatureType describeFt = describeFtAdapter.parse();
            Format format = determineFormat(requestVersion, describeFt.getOutputFormat(), "outputFormat");
            format.doDescribeFeatureType(describeFt, response, true);
            break;
        case DropStoredQuery:
            DropStoredQueryXMLAdapter dropStoredQueryAdapter = new DropStoredQueryXMLAdapter();
            dropStoredQueryAdapter.setRootElement(body);
            DropStoredQuery dropStoredQuery = dropStoredQueryAdapter.parse();
            storedQueryHandler.doDropStoredQuery(dropStoredQuery, response);
            break;
        case DescribeStoredQueries:
            DescribeStoredQueriesXMLAdapter describeStoredQueriesAdapter = new DescribeStoredQueriesXMLAdapter();
            describeStoredQueriesAdapter.setRootElement(body);
            DescribeStoredQueries describeStoredQueries = describeStoredQueriesAdapter.parse();
            storedQueryHandler.doDescribeStoredQueries(describeStoredQueries, response);
            break;
        case GetCapabilities:
            GetCapabilitiesXMLAdapter getCapabilitiesAdapter = new GetCapabilitiesXMLAdapter();
            getCapabilitiesAdapter.setRootElement(body);
            GetCapabilities wfsRequest = getCapabilitiesAdapter.parse(requestVersion);
            doGetCapabilities(wfsRequest, response);
            break;
        case GetFeature:
            GetFeatureXMLAdapter getFeatureAdapter = new GetFeatureXMLAdapter();
            getFeatureAdapter.setRootElement(body);
            GetFeature getFeature = getFeatureAdapter.parse();
            format = determineFormat(requestVersion, getFeature.getPresentationParams().getOutputFormat(),
                    "outputFormat");
            format.doGetFeature(getFeature, response);
            break;
        case GetFeatureWithLock:
            checkTransactionsEnabled(requestName);
            GetFeatureWithLockXMLAdapter getFeatureWithLockAdapter = new GetFeatureWithLockXMLAdapter();
            getFeatureWithLockAdapter.setRootElement(body);
            GetFeatureWithLock getFeatureWithLock = getFeatureWithLockAdapter.parse();
            format = determineFormat(requestVersion,
                    getFeatureWithLock.getPresentationParams().getOutputFormat(), "outputFormat");
            format.doGetFeature(getFeatureWithLock, response);
            break;
        case GetGmlObject:
            GetGmlObjectXMLAdapter getGmlObjectAdapter = new GetGmlObjectXMLAdapter();
            getGmlObjectAdapter.setRootElement(body);
            GetGmlObject getGmlObject = getGmlObjectAdapter.parse();
            format = determineFormat(requestVersion, getGmlObject.getOutputFormat(), "outputFormat");
            format.doGetGmlObject(getGmlObject, response);
            break;
        case GetPropertyValue:
            GetPropertyValueXMLAdapter getPropertyValueAdapter = new GetPropertyValueXMLAdapter();
            getPropertyValueAdapter.setRootElement(body);
            GetPropertyValue getPropertyValue = getPropertyValueAdapter.parse();
            format = determineFormat(requestVersion, getPropertyValue.getPresentationParams().getOutputFormat(),
                    "outputFormat");
            format.doGetPropertyValue(getPropertyValue, response);
            break;
        case ListStoredQueries:
            ListStoredQueriesXMLAdapter listStoredQueriesAdapter = new ListStoredQueriesXMLAdapter();
            listStoredQueriesAdapter.setRootElement(body);
            ListStoredQueries listStoredQueries = listStoredQueriesAdapter.parse();
            storedQueryHandler.doListStoredQueries(listStoredQueries, response);
            break;
        case LockFeature:
            checkTransactionsEnabled(requestName);
            LockFeatureXMLAdapter lockFeatureAdapter = new LockFeatureXMLAdapter();
            lockFeatureAdapter.setRootElement(body);
            LockFeature lockFeature = lockFeatureAdapter.parse();
            lockFeatureHandler.doLockFeature(lockFeature, response);
            break;
        case Transaction:
            checkTransactionsEnabled(requestName);
            TransactionXmlReader transactionReader = new TransactionXmlReaderFactory()
                    .createReader(requestVersion);
            Transaction transaction = transactionReader.read(bodyXmlStream);
            new TransactionHandler(this, service, transaction, idGenMode).doTransaction(response);
            break;
        default:
            throw new RuntimeException("Internal error: Unhandled request '" + requestName + "'.");
        }

        endSOAPResponse(response);

    } catch (OWSException e) {
        LOG.debug(e.getMessage(), e);
        sendSoapException(soapDoc, factory, response, e, request, requestVersion);
    } catch (XMLParsingException e) {
        LOG.trace("Stack trace:", e);
        sendSoapException(soapDoc, factory, response, new OWSException(e.getMessage(), INVALID_PARAMETER_VALUE),
                request, requestVersion);
    } catch (MissingParameterException e) {
        LOG.trace("Stack trace:", e);
        sendSoapException(soapDoc, factory, response, new OWSException(e), request, requestVersion);
    } catch (InvalidParameterValueException e) {
        LOG.trace("Stack trace:", e);
        sendSoapException(soapDoc, factory, response, new OWSException(e), request, requestVersion);
    } catch (Throwable e) {
        LOG.trace("Stack trace:", e);
        sendSoapException(soapDoc, factory, response, new OWSException(e.getMessage(), NO_APPLICABLE_CODE),
                request, requestVersion);
    }

}

From source file:org.deegree.services.wps.execute.ExecuteResponseXMLWriter.java

/**
 * Exports an {@link ExecuteResponse} object as a WPS 1.0.0 ExecuteResponse document.
 * /*from   www . ja  va2  s  .co  m*/
 * @param writer
 *            writer where the XML is written to
 * @param response
 *            object to be exported
 * @throws XMLStreamException
 */
public static void export100(XMLStreamWriter writer, ExecuteResponse response) throws XMLStreamException {

    // "wps:ExecuteResponse" (minOccurs="1", maxOccurs="1")
    writer.writeStartElement(WPS_PREFIX, "ExecuteResponse", WPS_NS);
    writer.writeNamespace(WPS_PREFIX, WPS_NS);
    writer.writeNamespace(OWS_PREFIX, OWS_NS);
    writer.writeNamespace(OGC_PREFIX, OGC_NS);
    writer.writeNamespace("xlink", XLN_NS);
    writer.writeNamespace("xsi", XSI_NS);

    writer.writeAttribute("service", "WPS");
    writer.writeAttribute("version", "1.0.0");
    writer.writeAttribute("xml:lang", "en");

    writer.writeAttribute(XSI_NS, "schemaLocation",
            "http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsExecute_response.xsd");

    // "serviceInstance" attribute (required)
    writer.writeAttribute("serviceInstance", response.getServiceInstance().toString());

    // "statusLocation" attribute (optional)
    if (response.getStatusLocation() != null) {
        writer.writeAttribute("statusLocation", "" + response.getStatusLocation().getWebURL());
    }

    // "wps:Process" element (minOccurs="1",maxOccurs="1")
    exportProcess(writer, response.getProcessDefinition());

    // "wps:Status" element (minOccurs="1",maxOccurs="1")
    exportStatus(writer, response.getExecutionStatus());

    // include inputs and output requests in the response?
    if (response.getLineage()) {
        // "wps:DataInputs" element (minOccurs="0",maxOccurs="1")
        exportDataInputs(writer, response);

        // "wps:OutputDefinitions" element (minOccurs="0",maxOccurs="1")
        exportOutputDefinitions(writer, response);
    }

    // "wps:ProcessOutputs" element (minOccurs="0",maxOccurs="1")
    if (response.getExecutionStatus().getExecutionState() == ExecutionState.SUCCEEDED) {
        // if process has finished successfully, include "wps:ProcessOutputs" element
        exportProcessOutputs(writer, response.getProcessOutputs(), response.getOutputDefinitions());
    }

    writer.writeEndElement(); // ExecuteResponse
}

From source file:org.exist.webdav.MiltonDocument.java

/**
 *  Serialize document properties/*w ww  . j a v a2 s.c o m*/
 * 
 * @param writer STAX writer
 * @throws XMLStreamException Thrown when writing data failed
 */
public void writeXML(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartElement("exist", "document", "http://exist.sourceforge.net/NS/exist");
    writer.writeAttribute("name", resourceXmldbUri.lastSegment().toString());
    writer.writeAttribute("created", getXmlDateTime(existDocument.getCreationTime()));
    writer.writeAttribute("last-modified", getXmlDateTime(existDocument.getLastModified()));
    writer.writeAttribute("owner", existDocument.getOwnerUser());
    writer.writeAttribute("group", existDocument.getOwnerGroup());
    writer.writeAttribute("permissions", "" + existDocument.getPermissions().toString());
    writer.writeAttribute("size", "" + existDocument.getContentLength());
    writer.writeEndElement();
}

From source file:org.flowable.bpmn.converter.export.BPMNDIExport.java

public static void writeBPMNDI(BpmnModel model, XMLStreamWriter xtw) throws Exception {
    // BPMN DI information
    xtw.writeStartElement(BPMNDI_PREFIX, ELEMENT_DI_DIAGRAM, BPMNDI_NAMESPACE);

    String processId = null;/*from  ww w  .j  av a  2  s. co  m*/
    if (!model.getPools().isEmpty()) {
        processId = "Collaboration";
    } else {
        processId = model.getMainProcess().getId();
    }

    xtw.writeAttribute(ATTRIBUTE_ID, "BPMNDiagram_" + processId);

    xtw.writeStartElement(BPMNDI_PREFIX, ELEMENT_DI_PLANE, BPMNDI_NAMESPACE);
    xtw.writeAttribute(ATTRIBUTE_DI_BPMNELEMENT, processId);
    xtw.writeAttribute(ATTRIBUTE_ID, "BPMNPlane_" + processId);

    for (String elementId : model.getLocationMap().keySet()) {

        if (model.getFlowElement(elementId) != null || model.getArtifact(elementId) != null
                || model.getPool(elementId) != null || model.getLane(elementId) != null) {

            xtw.writeStartElement(BPMNDI_PREFIX, ELEMENT_DI_SHAPE, BPMNDI_NAMESPACE);
            xtw.writeAttribute(ATTRIBUTE_DI_BPMNELEMENT, elementId);
            xtw.writeAttribute(ATTRIBUTE_ID, "BPMNShape_" + elementId);

            GraphicInfo graphicInfo = model.getGraphicInfo(elementId);
            FlowElement flowElement = model.getFlowElement(elementId);
            if (flowElement instanceof SubProcess && graphicInfo.getExpanded() != null) {
                xtw.writeAttribute(ATTRIBUTE_DI_IS_EXPANDED, String.valueOf(graphicInfo.getExpanded()));
            }

            xtw.writeStartElement(OMGDC_PREFIX, ELEMENT_DI_BOUNDS, OMGDC_NAMESPACE);
            xtw.writeAttribute(ATTRIBUTE_DI_HEIGHT, "" + graphicInfo.getHeight());
            xtw.writeAttribute(ATTRIBUTE_DI_WIDTH, "" + graphicInfo.getWidth());
            xtw.writeAttribute(ATTRIBUTE_DI_X, "" + graphicInfo.getX());
            xtw.writeAttribute(ATTRIBUTE_DI_Y, "" + graphicInfo.getY());
            xtw.writeEndElement();

            xtw.writeEndElement();
        }
    }

    for (String elementId : model.getFlowLocationMap().keySet()) {

        if (model.getFlowElement(elementId) != null || model.getArtifact(elementId) != null
                || model.getMessageFlow(elementId) != null) {

            xtw.writeStartElement(BPMNDI_PREFIX, ELEMENT_DI_EDGE, BPMNDI_NAMESPACE);
            xtw.writeAttribute(ATTRIBUTE_DI_BPMNELEMENT, elementId);
            xtw.writeAttribute(ATTRIBUTE_ID, "BPMNEdge_" + elementId);

            List<GraphicInfo> graphicInfoList = model.getFlowLocationGraphicInfo(elementId);
            for (GraphicInfo graphicInfo : graphicInfoList) {
                xtw.writeStartElement(OMGDI_PREFIX, ELEMENT_DI_WAYPOINT, OMGDI_NAMESPACE);
                xtw.writeAttribute(ATTRIBUTE_DI_X, "" + graphicInfo.getX());
                xtw.writeAttribute(ATTRIBUTE_DI_Y, "" + graphicInfo.getY());
                xtw.writeEndElement();
            }

            GraphicInfo labelGraphicInfo = model.getLabelGraphicInfo(elementId);
            FlowElement flowElement = model.getFlowElement(elementId);
            MessageFlow messageFlow = null;
            if (flowElement == null) {
                messageFlow = model.getMessageFlow(elementId);
            }

            boolean hasName = false;
            if (flowElement != null && StringUtils.isNotEmpty(flowElement.getName())) {
                hasName = true;

            } else if (messageFlow != null && StringUtils.isNotEmpty(messageFlow.getName())) {
                hasName = true;
            }

            if (labelGraphicInfo != null && hasName) {
                xtw.writeStartElement(BPMNDI_PREFIX, ELEMENT_DI_LABEL, BPMNDI_NAMESPACE);
                xtw.writeStartElement(OMGDC_PREFIX, ELEMENT_DI_BOUNDS, OMGDC_NAMESPACE);
                xtw.writeAttribute(ATTRIBUTE_DI_HEIGHT, "" + labelGraphicInfo.getHeight());
                xtw.writeAttribute(ATTRIBUTE_DI_WIDTH, "" + labelGraphicInfo.getWidth());
                xtw.writeAttribute(ATTRIBUTE_DI_X, "" + labelGraphicInfo.getX());
                xtw.writeAttribute(ATTRIBUTE_DI_Y, "" + labelGraphicInfo.getY());
                xtw.writeEndElement();
                xtw.writeEndElement();
            }

            xtw.writeEndElement();
        }
    }

    // end BPMN DI elements
    xtw.writeEndElement();
    xtw.writeEndElement();
}

From source file:org.flowable.bpmn.converter.export.FailedJobRetryCountExport.java

public static void writeFailedJobRetryCount(Activity activity, XMLStreamWriter xtw) throws Exception {
    String failedJobRetryCycle = activity.getFailedJobRetryTimeCycleValue();
    if (failedJobRetryCycle != null) {

        if (StringUtils.isNotEmpty(failedJobRetryCycle)) {
            xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, FAILED_JOB_RETRY_TIME_CYCLE,
                    FLOWABLE_EXTENSIONS_NAMESPACE);
            xtw.writeCharacters(failedJobRetryCycle);
            xtw.writeEndElement();//from  w w  w  .j ava  2s.  c o m
        }
    }
}

From source file:org.flowable.bpmn.converter.UserTaskXMLConverter.java

protected void writeCustomIdentities(UserTask userTask, String identityType, Set<String> users,
        Set<String> groups, XMLStreamWriter xtw) throws Exception {
    xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, ELEMENT_CUSTOM_RESOURCE, FLOWABLE_EXTENSIONS_NAMESPACE);
    writeDefaultAttribute(ATTRIBUTE_NAME, identityType, xtw);

    List<String> identityList = new ArrayList<String>();

    if (users != null) {
        for (String userId : users) {
            identityList.add("user(" + userId + ")");
        }/*from ww  w  .j  a va 2 s . c  o m*/
    }

    if (groups != null) {
        for (String groupId : groups) {
            identityList.add("group(" + groupId + ")");
        }
    }

    String delimitedString = convertToDelimitedString(identityList);

    xtw.writeStartElement(ELEMENT_RESOURCE_ASSIGNMENT);
    xtw.writeStartElement(ELEMENT_FORMAL_EXPRESSION);
    xtw.writeCharacters(delimitedString);
    xtw.writeEndElement(); // End ELEMENT_FORMAL_EXPRESSION
    xtw.writeEndElement(); // End ELEMENT_RESOURCE_ASSIGNMENT

    xtw.writeEndElement(); // End ELEMENT_CUSTOM_RESOURCE
}

From source file:org.flowable.cmmn.converter.util.CmmnXmlUtil.java

protected static void writeExtensionElement(ExtensionElement extensionElement, Map<String, String> namespaceMap,
        XMLStreamWriter xtw) throws Exception {
    if (StringUtils.isNotEmpty(extensionElement.getName())) {
        Map<String, String> localNamespaceMap = new HashMap<>();
        if (StringUtils.isNotEmpty(extensionElement.getNamespace())) {
            if (StringUtils.isNotEmpty(extensionElement.getNamespacePrefix())) {
                xtw.writeStartElement(extensionElement.getNamespacePrefix(), extensionElement.getName(),
                        extensionElement.getNamespace());

                if (!namespaceMap.containsKey(extensionElement.getNamespacePrefix()) || !namespaceMap
                        .get(extensionElement.getNamespacePrefix()).equals(extensionElement.getNamespace())) {

                    xtw.writeNamespace(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
                    namespaceMap.put(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
                    localNamespaceMap.put(extensionElement.getNamespacePrefix(),
                            extensionElement.getNamespace());
                }//from w  ww  . j  a  v a2 s.co  m
            } else {
                xtw.writeStartElement(extensionElement.getNamespace(), extensionElement.getName());
            }
        } else {
            xtw.writeStartElement(extensionElement.getName());
        }

        for (List<ExtensionAttribute> attributes : extensionElement.getAttributes().values()) {
            for (ExtensionAttribute attribute : attributes) {
                if (StringUtils.isNotEmpty(attribute.getName()) && attribute.getValue() != null) {
                    if (StringUtils.isNotEmpty(attribute.getNamespace())) {
                        if (StringUtils.isNotEmpty(attribute.getNamespacePrefix())) {

                            if (!namespaceMap.containsKey(attribute.getNamespacePrefix()) || !namespaceMap
                                    .get(attribute.getNamespacePrefix()).equals(attribute.getNamespace())) {

                                xtw.writeNamespace(attribute.getNamespacePrefix(), attribute.getNamespace());
                                namespaceMap.put(attribute.getNamespacePrefix(), attribute.getNamespace());
                            }

                            xtw.writeAttribute(attribute.getNamespacePrefix(), attribute.getNamespace(),
                                    attribute.getName(), attribute.getValue());
                        } else {
                            xtw.writeAttribute(attribute.getNamespace(), attribute.getName(),
                                    attribute.getValue());
                        }
                    } else {
                        xtw.writeAttribute(attribute.getName(), attribute.getValue());
                    }
                }
            }
        }

        if (extensionElement.getElementText() != null) {
            xtw.writeCData(extensionElement.getElementText());
        } else {
            for (List<ExtensionElement> childElements : extensionElement.getChildElements().values()) {
                for (ExtensionElement childElement : childElements) {
                    writeExtensionElement(childElement, namespaceMap, xtw);
                }
            }
        }

        for (String prefix : localNamespaceMap.keySet()) {
            namespaceMap.remove(prefix);
        }

        xtw.writeEndElement();
    }
}

From source file:org.gluu.saml.AuthRequest.java

public String getStreamedRequest(boolean useBase64) throws XMLStreamException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = factory.createXMLStreamWriter(baos);

    writer.writeStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeAttribute("ID", id);
    writer.writeAttribute("Version", "2.0");
    writer.writeAttribute("IssueInstant", this.issueInstant);
    writer.writeAttribute("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeAttribute("AssertionConsumerServiceURL", this.samlSettings.getAssertionConsumerServiceUrl());

    writer.writeStartElement("saml", "Issuer", "urn:oasis:names:tc:SAML:2.0:assertion");
    writer.writeNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    writer.writeCharacters(this.samlSettings.getIssuer());
    writer.writeEndElement();/*from  w ww. j av  a 2 s. com*/

    writer.writeStartElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeAttribute("Format", this.samlSettings.getNameIdentifierFormat());
    writer.writeAttribute("AllowCreate", "true");
    writer.writeEndElement();

    writer.writeStartElement("samlp", "RequestedAuthnContext", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeAttribute("Comparison", "exact");

    writer.writeStartElement("saml", "AuthnContextClassRef", "urn:oasis:names:tc:SAML:2.0:assertion");
    writer.writeNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    writer.writeCharacters("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    writer.writeEndElement();

    writer.writeEndElement();

    writer.writeEndElement();
    writer.flush();

    if (log.isDebugEnabled()) {
        log.debug("Genereated Saml Request " + new String(baos.toByteArray(), "UTF-8"));
    }

    if (useBase64) {
        byte[] deflated = CompressionHelper.deflate(baos.toByteArray(), true);
        String base64 = Base64.encodeBase64String(deflated);
        String encoded = URLEncoder.encode(base64, "UTF-8");

        return encoded;
    }

    return new String(baos.toByteArray(), "UTF-8");
}