com.sun.xml.ws.message.stream.StreamMessage Maven / Gradle / Ivy
Show all versions of rt Show documentation
/*
* Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.message.stream;
import com.sun.istack.NotNull;
import com.sun.istack.Nullable;
import com.sun.istack.XMLStreamReaderToContentHandler;
import com.sun.xml.stream.buffer.MutableXMLStreamBuffer;
import com.sun.xml.stream.buffer.XMLStreamBuffer;
import com.sun.xml.stream.buffer.XMLStreamBufferMark;
import com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator;
import com.sun.xml.ws.api.SOAPVersion;
import com.sun.xml.ws.api.message.AttachmentSet;
import com.sun.xml.ws.api.message.Header;
import com.sun.xml.ws.api.message.HeaderList;
import com.sun.xml.ws.api.message.Message;
import com.sun.xml.ws.api.message.MessageHeaders;
import com.sun.xml.ws.api.message.StreamingSOAP;
import com.sun.xml.ws.api.streaming.XMLStreamReaderFactory;
import com.sun.xml.ws.encoding.TagInfoset;
import com.sun.xml.ws.message.AbstractMessageImpl;
import com.sun.xml.ws.message.AttachmentUnmarshallerImpl;
import com.sun.xml.ws.protocol.soap.VersionMismatchException;
import com.sun.xml.ws.spi.db.XMLBridge;
import com.sun.xml.ws.streaming.XMLStreamReaderUtil;
import com.sun.xml.ws.util.xml.DummyLocation;
import com.sun.xml.ws.util.xml.StAXSource;
import com.sun.xml.ws.util.xml.XMLReaderComposite;
import org.jvnet.staxex.util.XMLStreamReaderToXMLStreamWriter;
import com.sun.xml.ws.util.xml.XMLReaderComposite.ElemInfo;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.NamespaceSupport;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.transform.Source;
import jakarta.xml.ws.WebServiceException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* {@link Message} implementation backed by {@link XMLStreamReader}.
*
* TODO: we need another message class that keeps {@link XMLStreamReader} that points
* at the start of the envelope element.
*/
public class StreamMessage extends AbstractMessageImpl implements StreamingSOAP {
/**
* The reader will be positioned at
* the first child of the SOAP body
*/
private @NotNull XMLStreamReader reader;
// lazily created
private @Nullable MessageHeaders headers;
/**
* Because the StreamMessage leaves out the white spaces around payload
* when being instantiated the space characters between soap:Body opening and
* payload is stored in this field to be reused later (necessary for message security);
* Instantiated after StreamMessage creation
*/
private String bodyPrologue = null;
/**
* instantiated after writing message to XMLStreamWriter
*/
private String bodyEpilogue = null;
private String payloadLocalName;
private String payloadNamespaceURI;
/**
* Used only for debugging. This records where the message was consumed.
*/
private Throwable consumedAt;
private XMLStreamReader envelopeReader;
public StreamMessage(SOAPVersion v) {
super(v);
payloadLocalName = null;
payloadNamespaceURI = null;
}
public StreamMessage(SOAPVersion v, @NotNull XMLStreamReader envelope, @NotNull AttachmentSet attachments) {
super(v);
envelopeReader = envelope;
attachmentSet = attachments;
}
@Override
public XMLStreamReader readEnvelope() {
if (envelopeReader == null) {
List hReaders = new java.util.ArrayList<>();
ElemInfo envElem = new ElemInfo(envelopeTag, null);
ElemInfo hdrElem = (headerTag != null) ? new ElemInfo(headerTag, envElem) : null;
ElemInfo bdyElem = new ElemInfo(bodyTag, envElem);
for (Header h : getHeaders().asList()) {
try {
hReaders.add(h.readHeader());
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
XMLStreamReader soapHeader = (hdrElem != null) ? new XMLReaderComposite(hdrElem, hReaders.toArray(new XMLStreamReader[0])) : null;
XMLStreamReader[] payload = {readPayload()};
XMLStreamReader soapBody = new XMLReaderComposite(bdyElem, payload);
XMLStreamReader[] soapContent = (soapHeader != null) ? new XMLStreamReader[]{soapHeader, soapBody} : new XMLStreamReader[]{soapBody};
return new XMLReaderComposite(envElem, soapContent);
}
return envelopeReader;
}
/**
* Creates a {@link StreamMessage} from a {@link XMLStreamReader}
* that points at the start element of the payload, and headers.
*
*
* This method creates a {@link Message} from a payload.
*
* @param headers
* if null, it means no headers. if non-null,
* it will be owned by this message.
* @param reader
* points at the start element/document of the payload (or the end element of the <s:Body>
* if there's no payload)
*/
public StreamMessage(@Nullable MessageHeaders headers, @NotNull AttachmentSet attachmentSet, @NotNull XMLStreamReader reader, @NotNull SOAPVersion soapVersion) {
super(soapVersion);
init(headers, attachmentSet, reader, soapVersion);
}
private void init(@Nullable MessageHeaders headers, @NotNull AttachmentSet attachmentSet, @NotNull XMLStreamReader reader, @NotNull SOAPVersion soapVersion) {
this.headers = headers;
this.attachmentSet = attachmentSet;
this.reader = reader;
if(reader.getEventType()== XMLStreamConstants.START_DOCUMENT)
XMLStreamReaderUtil.nextElementContent(reader);
//if the reader is pointing to the end element then its empty message
// or no payload
if(reader.getEventType() == XMLStreamConstants.END_ELEMENT){
String body = reader.getLocalName();
String nsUri = reader.getNamespaceURI();
assert body != null;
assert nsUri != null;
//if its not soapenv:Body then throw exception, we received malformed stream
if(body.equals("Body") && nsUri.equals(soapVersion.nsUri)){
this.payloadLocalName = null;
this.payloadNamespaceURI = null;
}else{ //TODO: i18n and also we should be throwing better message that this
throw new WebServiceException("Malformed stream: {"+nsUri+"}"+body);
}
}else{
this.payloadLocalName = reader.getLocalName();
this.payloadNamespaceURI = reader.getNamespaceURI();
}
// use the default infoset representation for headers
int base = soapVersion.ordinal()*3;
this.envelopeTag = DEFAULT_TAGS.get(base);
this.headerTag = DEFAULT_TAGS.get(base+1);
this.bodyTag = DEFAULT_TAGS.get(base+2);
}
/**
* Creates a {@link StreamMessage} from a {@link XMLStreamReader}
* and the complete infoset of the SOAP envelope.
*
*
* See {@link #StreamMessage(MessageHeaders, AttachmentSet, XMLStreamReader, SOAPVersion)} for
* the description of the basic parameters.
*
* @param headerTag
* Null if the message didn't have a header tag.
*
*/
public StreamMessage(@NotNull TagInfoset envelopeTag, @Nullable TagInfoset headerTag, @NotNull AttachmentSet attachmentSet, @Nullable MessageHeaders headers, @NotNull TagInfoset bodyTag, @NotNull XMLStreamReader reader, @NotNull SOAPVersion soapVersion) {
this(envelopeTag, headerTag, attachmentSet, headers, null, bodyTag, null, reader, soapVersion);
}
public StreamMessage(@NotNull TagInfoset envelopeTag, @Nullable TagInfoset headerTag, @NotNull AttachmentSet attachmentSet, @Nullable MessageHeaders headers, @Nullable String bodyPrologue, @NotNull TagInfoset bodyTag, @Nullable String bodyEpilogue, @NotNull XMLStreamReader reader, @NotNull SOAPVersion soapVersion) {
super(soapVersion);
init(envelopeTag, headerTag, attachmentSet, headers, bodyPrologue, bodyTag, bodyEpilogue, reader, soapVersion);
}
private void init(@NotNull TagInfoset envelopeTag, @Nullable TagInfoset headerTag, @NotNull AttachmentSet attachmentSet, @Nullable MessageHeaders headers, @Nullable String bodyPrologue, @NotNull TagInfoset bodyTag, @Nullable String bodyEpilogue, @NotNull XMLStreamReader reader, @NotNull SOAPVersion soapVersion) {
init(headers,attachmentSet,reader,soapVersion);
if(envelopeTag == null ) {
throw new IllegalArgumentException("EnvelopeTag TagInfoset cannot be null");
}
if(bodyTag == null ) {
throw new IllegalArgumentException("BodyTag TagInfoset cannot be null");
}
this.envelopeTag = envelopeTag;
this.headerTag = headerTag;
this.bodyTag = bodyTag;
this.bodyPrologue = bodyPrologue;
this.bodyEpilogue = bodyEpilogue;
}
@Override
public boolean hasHeaders() {
if ( envelopeReader != null ) readEnvelope(this);
return headers!=null && headers.hasHeaders();
}
@Override
public MessageHeaders getHeaders() {
if ( envelopeReader != null ) readEnvelope(this);
if (headers == null) {
headers = new HeaderList(getSOAPVersion());
}
return headers;
}
@Override
public String getPayloadLocalPart() {
if ( envelopeReader != null ) readEnvelope(this);
return payloadLocalName;
}
@Override
public String getPayloadNamespaceURI() {
if ( envelopeReader != null ) readEnvelope(this);
return payloadNamespaceURI;
}
@Override
public boolean hasPayload() {
if ( envelopeReader != null ) readEnvelope(this);
return payloadLocalName!=null;
}
@Override
public Source readPayloadAsSource() {
if(hasPayload()) {
assert unconsumed();
return new StAXSource(reader, true, getInscopeNamespaces());
} else
return null;
}
/**
* There is no way to enumerate inscope namespaces for XMLStreamReader. That means
* namespaces declared in envelope, and body tags need to be computed using their
* {@link TagInfoset}s.
*
* @return array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
*/
private String[] getInscopeNamespaces() {
NamespaceSupport nss = new NamespaceSupport();
nss.pushContext();
for(int i=0; i < envelopeTag.ns.length; i+=2) {
nss.declarePrefix(envelopeTag.ns[i], envelopeTag.ns[i+1]);
}
nss.pushContext();
for(int i=0; i < bodyTag.ns.length; i+=2) {
nss.declarePrefix(bodyTag.ns[i], bodyTag.ns[i+1]);
}
List inscope = new ArrayList<>();
for( Enumeration en = nss.getPrefixes(); en.hasMoreElements(); ) {
String prefix = (String)en.nextElement();
inscope.add(prefix);
inscope.add(nss.getURI(prefix));
}
return inscope.toArray(new String[0]);
}
@Override
@SuppressWarnings({"unchecked"})
public T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
if(!hasPayload())
return null;
assert unconsumed();
// TODO: How can the unmarshaller process this as a fragment?
if(hasAttachments())
unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
try {
return (T) unmarshaller.unmarshal(reader);
} finally{
unmarshaller.setAttachmentUnmarshaller(null);
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
}
}
@Override
public T readPayloadAsJAXB(XMLBridge bridge) throws JAXBException {
if(!hasPayload())
return null;
assert unconsumed();
T r = bridge.unmarshal(reader,
hasAttachments() ? new AttachmentUnmarshallerImpl(getAttachments()) : null);
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
return r;
}
@Override
public void consume() {
assert unconsumed();
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
}
@Override
public XMLStreamReader readPayload() {
if(!hasPayload())
return null;
// TODO: What about access at and beyond
assert unconsumed();
return this.reader;
}
@Override
public void writePayloadTo(XMLStreamWriter writer)throws XMLStreamException {
if ( envelopeReader != null ) readEnvelope(this);
assert unconsumed();
if(payloadLocalName==null) {
return; // no body
}
if (bodyPrologue != null) {
writer.writeCharacters(bodyPrologue);
}
XMLStreamReaderToXMLStreamWriter conv = new XMLStreamReaderToXMLStreamWriter();
while(reader.getEventType() != XMLStreamConstants.END_DOCUMENT){
String name = reader.getLocalName();
String nsUri = reader.getNamespaceURI();
// After previous conv.bridge() call the cursor will be at END_ELEMENT.
// Check if its not soapenv:Body then move to next ELEMENT
if(reader.getEventType() == XMLStreamConstants.END_ELEMENT){
if (!isBodyElement(name, nsUri)){
// closing payload element: store epilogue for further signing, if applicable
// however if there more than one payloads exist - the last one is stored
String whiteSpaces = XMLStreamReaderUtil.nextWhiteSpaceContent(reader);
if (whiteSpaces != null) {
this.bodyEpilogue = whiteSpaces;
// write it to the message too
writer.writeCharacters(whiteSpaces);
}
} else {
// body closed > exit
break;
}
} else {
// payload opening element: copy payload to writer
conv.bridge(reader,writer);
}
}
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
}
private boolean isBodyElement(String name, String nsUri) {
return name.equals("Body") && nsUri.equals(soapVersion.nsUri);
}
@Override
public void writeTo(XMLStreamWriter sw) throws XMLStreamException{
if ( envelopeReader != null ) readEnvelope(this);
writeEnvelope(sw);
}
@Override
public void writeToBodyStart(XMLStreamWriter writer) throws XMLStreamException {
if ( envelopeReader != null ) readEnvelope(this);
writer.writeStartDocument();
envelopeTag.writeStart(writer);
//write headers
MessageHeaders hl = getHeaders();
if (hl.hasHeaders() && headerTag == null) headerTag = new TagInfoset(envelopeTag.nsUri,"Header",envelopeTag.prefix,EMPTY_ATTS);
if (headerTag != null) {
headerTag.writeStart(writer);
if (hl.hasHeaders()){
for(Header h : hl.asList()){
h.writeTo(writer);
}
}
writer.writeEndElement();
}
bodyTag.writeStart(writer);
}
/**
* This method should be called when the StreamMessage is created with a payload
*/
private void writeEnvelope(XMLStreamWriter writer) throws XMLStreamException {
writeToBodyStart(writer);
if(hasPayload())
writePayloadTo(writer);
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndDocument();
}
@Override
public void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
if ( envelopeReader != null ) readEnvelope(this);
assert unconsumed();
try {
if(payloadLocalName==null)
return; // no body
if (bodyPrologue != null) {
char[] chars = bodyPrologue.toCharArray();
contentHandler.characters(chars, 0, chars.length);
}
XMLStreamReaderToContentHandler conv = new XMLStreamReaderToContentHandler(reader,contentHandler,true,fragment,getInscopeNamespaces());
while(reader.getEventType() != XMLStreamConstants.END_DOCUMENT){
String name = reader.getLocalName();
String nsUri = reader.getNamespaceURI();
// After previous conv.bridge() call the cursor will be at END_ELEMENT.
// Check if its not soapenv:Body then move to next ELEMENT
if(reader.getEventType() == XMLStreamConstants.END_ELEMENT){
if (!isBodyElement(name, nsUri)){
// closing payload element: store epilogue for further signing, if applicable
// however if there more than one payloads exist - the last one is stored
String whiteSpaces = XMLStreamReaderUtil.nextWhiteSpaceContent(reader);
if (whiteSpaces != null) {
this.bodyEpilogue = whiteSpaces;
// write it to the message too
char[] chars = whiteSpaces.toCharArray();
contentHandler.characters(chars, 0, chars.length);
}
} else {
// body closed > exit
break;
}
} else {
// payload opening element: copy payload to writer
conv.bridge();
}
}
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
} catch (XMLStreamException e) {
Location loc = e.getLocation();
if(loc==null) loc = DummyLocation.INSTANCE;
SAXParseException x = new SAXParseException(
e.getMessage(),loc.getPublicId(),loc.getSystemId(),loc.getLineNumber(),loc.getColumnNumber(),e);
errorHandler.error(x);
}
}
// TODO: this method should be probably rewritten to respect spaces between elements; is it used at all?
@Override
public Message copy() {
if ( envelopeReader != null ) readEnvelope(this);
try {
assert unconsumed();
consumedAt = null; // but we don't want to mark it as consumed
MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();
StreamReaderBufferCreator c = new StreamReaderBufferCreator(xsb);
// preserving inscope namespaces from envelope, and body. Other option
// would be to create a filtering XMLStreamReader from reader+envelopeTag+bodyTag
c.storeElement(envelopeTag.nsUri, envelopeTag.localName, envelopeTag.prefix, envelopeTag.ns);
c.storeElement(bodyTag.nsUri, bodyTag.localName, bodyTag.prefix, bodyTag.ns);
if (hasPayload()) {
// Loop all the way for multi payload case
while(reader.getEventType() != XMLStreamConstants.END_DOCUMENT){
String name = reader.getLocalName();
String nsUri = reader.getNamespaceURI();
if(isBodyElement(name, nsUri) || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT))
break;
c.create(reader);
// Skip whitespaces in between payload and