src/share/jaxws_classes/com/sun/xml/internal/ws/message/saaj/SAAJMessage.java

changeset 0
373ffda63c9a
child 637
9c07ef4934dd
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/jaxws_classes/com/sun/xml/internal/ws/message/saaj/SAAJMessage.java	Wed Apr 27 01:27:09 2016 +0800
     1.3 @@ -0,0 +1,778 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package com.sun.xml.internal.ws.message.saaj;
    1.30 +
    1.31 +import com.sun.istack.internal.FragmentContentHandler;
    1.32 +import com.sun.istack.internal.NotNull;
    1.33 +import com.sun.istack.internal.Nullable;
    1.34 +import com.sun.istack.internal.XMLStreamException2;
    1.35 +import com.sun.xml.internal.bind.api.Bridge;
    1.36 +import com.sun.xml.internal.bind.unmarshaller.DOMScanner;
    1.37 +import com.sun.xml.internal.ws.api.SOAPVersion;
    1.38 +import com.sun.xml.internal.ws.api.message.*;
    1.39 +import com.sun.xml.internal.ws.message.AttachmentUnmarshallerImpl;
    1.40 +import com.sun.xml.internal.ws.spi.db.XMLBridge;
    1.41 +import com.sun.xml.internal.ws.streaming.DOMStreamReader;
    1.42 +import com.sun.xml.internal.ws.util.ASCIIUtility;
    1.43 +import com.sun.xml.internal.ws.util.DOMUtil;
    1.44 +import org.w3c.dom.Attr;
    1.45 +import org.w3c.dom.Element;
    1.46 +import org.w3c.dom.NamedNodeMap;
    1.47 +import org.w3c.dom.Node;
    1.48 +import org.xml.sax.ContentHandler;
    1.49 +import org.xml.sax.ErrorHandler;
    1.50 +import org.xml.sax.SAXException;
    1.51 +import org.xml.sax.helpers.AttributesImpl;
    1.52 +import org.xml.sax.helpers.LocatorImpl;
    1.53 +
    1.54 +import javax.activation.DataHandler;
    1.55 +import javax.xml.bind.JAXBException;
    1.56 +import javax.xml.bind.Unmarshaller;
    1.57 +import javax.xml.soap.*;
    1.58 +import javax.xml.stream.XMLStreamException;
    1.59 +import javax.xml.stream.XMLStreamReader;
    1.60 +import javax.xml.stream.XMLStreamWriter;
    1.61 +import javax.xml.transform.Source;
    1.62 +import javax.xml.transform.dom.DOMSource;
    1.63 +import javax.xml.transform.stream.StreamSource;
    1.64 +import javax.xml.ws.WebServiceException;
    1.65 +import java.io.IOException;
    1.66 +import java.io.InputStream;
    1.67 +import java.io.OutputStream;
    1.68 +import java.util.HashMap;
    1.69 +import java.util.Iterator;
    1.70 +import java.util.List;
    1.71 +import java.util.Map;
    1.72 +
    1.73 +/**
    1.74 + * {@link Message} implementation backed by {@link SOAPMessage}.
    1.75 + *
    1.76 + * @author Vivek Pandey
    1.77 + * @author Rama Pulavarthi
    1.78 + */
    1.79 +public class SAAJMessage extends Message {
    1.80 +    // flag to switch between representations
    1.81 +    private boolean parsedMessage;
    1.82 +    // flag to check if Message API is exercised;
    1.83 +    private boolean accessedMessage;
    1.84 +    private final SOAPMessage sm;
    1.85 +
    1.86 +    private MessageHeaders headers;
    1.87 +    private List<Element> bodyParts;
    1.88 +    private Element payload;
    1.89 +
    1.90 +    private String payloadLocalName;
    1.91 +    private String payloadNamespace;
    1.92 +    private SOAPVersion soapVersion;
    1.93 +
    1.94 +    //Collect the attrbutes on the enclosing elements so that the same message can be reproduced without loss of any
    1.95 +    // valuable info
    1.96 +    private NamedNodeMap bodyAttrs, headerAttrs, envelopeAttrs;
    1.97 +
    1.98 +    public SAAJMessage(SOAPMessage sm) {
    1.99 +        this.sm = sm;
   1.100 +    }
   1.101 +
   1.102 +    /**
   1.103 +     * This constructor is a convenience and called by the {@link #copy}
   1.104 +     *
   1.105 +     * @param headers
   1.106 +     * @param sm
   1.107 +     */
   1.108 +    private SAAJMessage(MessageHeaders headers, AttachmentSet as, SOAPMessage sm, SOAPVersion version) {
   1.109 +        this.sm = sm;
   1.110 +        this.parse();
   1.111 +        if(headers == null)
   1.112 +            headers = new HeaderList(version);
   1.113 +        this.headers = headers;
   1.114 +        this.attachmentSet = as;
   1.115 +    }
   1.116 +
   1.117 +    private void parse() {
   1.118 +        if (!parsedMessage) {
   1.119 +            try {
   1.120 +                access();
   1.121 +                if (headers == null)
   1.122 +                    headers = new HeaderList(getSOAPVersion());
   1.123 +                SOAPHeader header = sm.getSOAPHeader();
   1.124 +                if (header != null) {
   1.125 +                    headerAttrs = header.getAttributes();
   1.126 +                    Iterator iter = header.examineAllHeaderElements();
   1.127 +                    while (iter.hasNext()) {
   1.128 +                        headers.add(new SAAJHeader((SOAPHeaderElement) iter.next()));
   1.129 +                    }
   1.130 +                }
   1.131 +                attachmentSet = new SAAJAttachmentSet(sm);
   1.132 +
   1.133 +                parsedMessage = true;
   1.134 +            } catch (SOAPException e) {
   1.135 +                throw new WebServiceException(e);
   1.136 +            }
   1.137 +        }
   1.138 +    }
   1.139 +
   1.140 +    protected void access() {
   1.141 +        if (!accessedMessage) {
   1.142 +            try {
   1.143 +                envelopeAttrs = sm.getSOAPPart().getEnvelope().getAttributes();
   1.144 +                Node body = sm.getSOAPBody();
   1.145 +                bodyAttrs = body.getAttributes();
   1.146 +                soapVersion = SOAPVersion.fromNsUri(body.getNamespaceURI());
   1.147 +                //cature all the body elements
   1.148 +                bodyParts = DOMUtil.getChildElements(body);
   1.149 +                //we treat payload as the first body part
   1.150 +                payload = bodyParts.size() > 0 ? bodyParts.get(0) : null;
   1.151 +                // hope this is correct. Caching the localname and namespace of the payload should be fine
   1.152 +                // but what about if a Handler replaces the payload with something else? Weel, may be it
   1.153 +                // will be error condition anyway
   1.154 +                if (payload != null) {
   1.155 +                    payloadLocalName = payload.getLocalName();
   1.156 +                    payloadNamespace = payload.getNamespaceURI();
   1.157 +                }
   1.158 +                accessedMessage = true;
   1.159 +            } catch (SOAPException e) {
   1.160 +                throw new WebServiceException(e);
   1.161 +            }
   1.162 +        }
   1.163 +    }
   1.164 +
   1.165 +    public boolean hasHeaders() {
   1.166 +        parse();
   1.167 +        return headers.hasHeaders();
   1.168 +    }
   1.169 +
   1.170 +    public @NotNull MessageHeaders getHeaders() {
   1.171 +        parse();
   1.172 +        return headers;
   1.173 +    }
   1.174 +
   1.175 +    /**
   1.176 +     * Gets the attachments of this message
   1.177 +     * (attachments live outside a message.)
   1.178 +     */
   1.179 +    @Override
   1.180 +    public @NotNull AttachmentSet getAttachments() {
   1.181 +        if (attachmentSet == null) attachmentSet = new SAAJAttachmentSet(sm);
   1.182 +        return attachmentSet;
   1.183 +    }
   1.184 +
   1.185 +    /**
   1.186 +     * Optimization hint for the derived class to check
   1.187 +     * if we may have some attachments.
   1.188 +     */
   1.189 +    @Override
   1.190 +    protected boolean hasAttachments() {
   1.191 +        return !getAttachments().isEmpty();
   1.192 +    }
   1.193 +
   1.194 +    public @Nullable String getPayloadLocalPart() {
   1.195 +        soapBodyFirstChild();
   1.196 +        return payloadLocalName;
   1.197 +    }
   1.198 +
   1.199 +    public String getPayloadNamespaceURI() {
   1.200 +        soapBodyFirstChild();
   1.201 +        return payloadNamespace;
   1.202 +    }
   1.203 +
   1.204 +    public boolean hasPayload() {
   1.205 +        return soapBodyFirstChild() != null;
   1.206 +    }
   1.207 +
   1.208 +    private void addAttributes(Element e, NamedNodeMap attrs) {
   1.209 +        if(attrs == null)
   1.210 +            return;
   1.211 +        String elPrefix = e.getPrefix();
   1.212 +        for(int i=0; i < attrs.getLength();i++) {
   1.213 +            Attr a = (Attr)attrs.item(i);
   1.214 +            //check if attr is ns declaration
   1.215 +            if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
   1.216 +                if(elPrefix == null && a.getLocalName().equals("xmlns")) {
   1.217 +                    // the target element has already default ns declaration, dont' override it
   1.218 +                    continue;
   1.219 +                } else if(elPrefix != null && "xmlns".equals(a.getPrefix()) && elPrefix.equals(a.getLocalName())) {
   1.220 +                    //dont bind the prefix to ns again, its already in the target element.
   1.221 +                    continue;
   1.222 +                }
   1.223 +                e.setAttributeNS(a.getNamespaceURI(),a.getName(),a.getValue());
   1.224 +                continue;
   1.225 +            }
   1.226 +            e.setAttributeNS(a.getNamespaceURI(),a.getName(),a.getValue());
   1.227 +        }
   1.228 +    }
   1.229 +
   1.230 +    public Source readEnvelopeAsSource() {
   1.231 +        try {
   1.232 +            if (!parsedMessage) {
   1.233 +                SOAPEnvelope se = sm.getSOAPPart().getEnvelope();
   1.234 +                return new DOMSource(se);
   1.235 +
   1.236 +            } else {
   1.237 +                                SOAPMessage msg = soapVersion.getMessageFactory().createMessage();
   1.238 +                addAttributes(msg.getSOAPPart().getEnvelope(),envelopeAttrs);
   1.239 +
   1.240 +                SOAPBody newBody = msg.getSOAPPart().getEnvelope().getBody();
   1.241 +                addAttributes(newBody, bodyAttrs);
   1.242 +                for (Element part : bodyParts) {
   1.243 +                    Node n = newBody.getOwnerDocument().importNode(part, true);
   1.244 +                    newBody.appendChild(n);
   1.245 +                }
   1.246 +                addAttributes(msg.getSOAPHeader(),headerAttrs);
   1.247 +                for (Header header : headers.asList()) {
   1.248 +                    header.writeTo(msg);
   1.249 +                }
   1.250 +                SOAPEnvelope se = msg.getSOAPPart().getEnvelope();
   1.251 +                return new DOMSource(se);
   1.252 +            }
   1.253 +        } catch (SOAPException e) {
   1.254 +            throw new WebServiceException(e);
   1.255 +        }
   1.256 +    }
   1.257 +
   1.258 +    public SOAPMessage readAsSOAPMessage() throws SOAPException {
   1.259 +        if (!parsedMessage) {
   1.260 +            return sm;
   1.261 +        } else {
   1.262 +            SOAPMessage msg = soapVersion.getMessageFactory().createMessage();
   1.263 +            addAttributes(msg.getSOAPPart().getEnvelope(),envelopeAttrs);
   1.264 +            SOAPBody newBody = msg.getSOAPPart().getEnvelope().getBody();
   1.265 +            addAttributes(newBody, bodyAttrs);
   1.266 +            for (Element part : bodyParts) {
   1.267 +                Node n = newBody.getOwnerDocument().importNode(part, true);
   1.268 +                newBody.appendChild(n);
   1.269 +            }
   1.270 +            addAttributes(msg.getSOAPHeader(),headerAttrs);
   1.271 +            for (Header header : headers.asList()) {
   1.272 +              header.writeTo(msg);
   1.273 +            }
   1.274 +            for (Attachment att : getAttachments()) {
   1.275 +              AttachmentPart part = msg.createAttachmentPart();
   1.276 +              part.setDataHandler(att.asDataHandler());
   1.277 +              part.setContentId('<' + att.getContentId() + '>');
   1.278 +              addCustomMimeHeaders(att, part);
   1.279 +              msg.addAttachmentPart(part);
   1.280 +            }
   1.281 +            msg.saveChanges();
   1.282 +            return msg;
   1.283 +        }
   1.284 +    }
   1.285 +
   1.286 +        private void addCustomMimeHeaders(Attachment att, AttachmentPart part) {
   1.287 +                if (att instanceof AttachmentEx) {
   1.288 +                        Iterator<AttachmentEx.MimeHeader> allMimeHeaders = ((AttachmentEx) att).getMimeHeaders();
   1.289 +                        while (allMimeHeaders.hasNext()) {
   1.290 +                                AttachmentEx.MimeHeader mh = allMimeHeaders.next();
   1.291 +                                String name = mh.getName();
   1.292 +                                if (!"Content-Type".equalsIgnoreCase(name)
   1.293 +                                                && !"Content-Id".equalsIgnoreCase(name)) {
   1.294 +                                        part.addMimeHeader(name, mh.getValue());
   1.295 +                                }
   1.296 +                        }
   1.297 +                }
   1.298 +        }
   1.299 +
   1.300 +    public Source readPayloadAsSource() {
   1.301 +        access();
   1.302 +        return (payload != null) ? new DOMSource(payload) : null;
   1.303 +    }
   1.304 +
   1.305 +    public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
   1.306 +        access();
   1.307 +        if (payload != null) {
   1.308 +            if(hasAttachments())
   1.309 +                unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
   1.310 +            return (T) unmarshaller.unmarshal(payload);
   1.311 +
   1.312 +        }
   1.313 +        return null;
   1.314 +    }
   1.315 +
   1.316 +    /** @deprecated */
   1.317 +    public <T> T readPayloadAsJAXB(Bridge<T> bridge) throws JAXBException {
   1.318 +        access();
   1.319 +        if (payload != null)
   1.320 +            return bridge.unmarshal(payload,hasAttachments()? new AttachmentUnmarshallerImpl(getAttachments()) : null);
   1.321 +        return null;
   1.322 +    }
   1.323 +    public <T> T readPayloadAsJAXB(XMLBridge<T> bridge) throws JAXBException {
   1.324 +        access();
   1.325 +        if (payload != null)
   1.326 +            return bridge.unmarshal(payload,hasAttachments()? new AttachmentUnmarshallerImpl(getAttachments()) : null);
   1.327 +        return null;
   1.328 +    }
   1.329 +
   1.330 +    public XMLStreamReader readPayload() throws XMLStreamException {
   1.331 +        return soapBodyFirstChildReader();
   1.332 +    }
   1.333 +
   1.334 +    public void writePayloadTo(XMLStreamWriter sw) throws XMLStreamException {
   1.335 +        access();
   1.336 +        try {
   1.337 +            for (Element part : bodyParts)
   1.338 +                DOMUtil.serializeNode(part, sw);
   1.339 +        } catch (XMLStreamException e) {
   1.340 +            throw new WebServiceException(e);
   1.341 +        }
   1.342 +    }
   1.343 +
   1.344 +    public void writeTo(XMLStreamWriter writer) throws XMLStreamException {
   1.345 +        try {
   1.346 +            writer.writeStartDocument();
   1.347 +            if (!parsedMessage) {
   1.348 +                DOMUtil.serializeNode(sm.getSOAPPart().getEnvelope(), writer);
   1.349 +            } else {
   1.350 +                SOAPEnvelope env = sm.getSOAPPart().getEnvelope();
   1.351 +                DOMUtil.writeTagWithAttributes(env, writer);
   1.352 +                if (hasHeaders()) {
   1.353 +                    if(env.getHeader() != null) {
   1.354 +                        DOMUtil.writeTagWithAttributes(env.getHeader(), writer);
   1.355 +                    } else {
   1.356 +                        writer.writeStartElement(env.getPrefix(), "Header", env.getNamespaceURI());
   1.357 +                    }
   1.358 +                    for (Header h : headers.asList()) {
   1.359 +                        h.writeTo(writer);
   1.360 +                    }
   1.361 +                    writer.writeEndElement();
   1.362 +                }
   1.363 +
   1.364 +                DOMUtil.serializeNode(sm.getSOAPBody(), writer);
   1.365 +                writer.writeEndElement();
   1.366 +            }
   1.367 +            writer.writeEndDocument();
   1.368 +            writer.flush();
   1.369 +        } catch (SOAPException ex) {
   1.370 +            throw new XMLStreamException2(ex);
   1.371 +            //for now. ask jaxws team what to do.
   1.372 +        }
   1.373 +    }
   1.374 +
   1.375 +    public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler) throws SAXException {
   1.376 +        String soapNsUri = soapVersion.nsUri;
   1.377 +        if (!parsedMessage) {
   1.378 +            DOMScanner ds = new DOMScanner();
   1.379 +            ds.setContentHandler(contentHandler);
   1.380 +            ds.scan(sm.getSOAPPart());
   1.381 +        } else {
   1.382 +            contentHandler.setDocumentLocator(NULL_LOCATOR);
   1.383 +            contentHandler.startDocument();
   1.384 +            contentHandler.startPrefixMapping("S", soapNsUri);
   1.385 +            startPrefixMapping(contentHandler, envelopeAttrs,"S");
   1.386 +            contentHandler.startElement(soapNsUri, "Envelope", "S:Envelope", getAttributes(envelopeAttrs));
   1.387 +            if (hasHeaders()) {
   1.388 +                startPrefixMapping(contentHandler, headerAttrs,"S");
   1.389 +                contentHandler.startElement(soapNsUri, "Header", "S:Header", getAttributes(headerAttrs));
   1.390 +                MessageHeaders headers = getHeaders();
   1.391 +                for (Header h : headers.asList()) {
   1.392 +                    h.writeTo(contentHandler, errorHandler);
   1.393 +                }
   1.394 +                endPrefixMapping(contentHandler, headerAttrs,"S");
   1.395 +                contentHandler.endElement(soapNsUri, "Header", "S:Header");
   1.396 +
   1.397 +            }
   1.398 +            startPrefixMapping(contentHandler, bodyAttrs,"S");
   1.399 +            // write the body
   1.400 +            contentHandler.startElement(soapNsUri, "Body", "S:Body", getAttributes(bodyAttrs));
   1.401 +            writePayloadTo(contentHandler, errorHandler, true);
   1.402 +            endPrefixMapping(contentHandler, bodyAttrs,"S");
   1.403 +            contentHandler.endElement(soapNsUri, "Body", "S:Body");
   1.404 +            endPrefixMapping(contentHandler, envelopeAttrs,"S");
   1.405 +            contentHandler.endElement(soapNsUri, "Envelope", "S:Envelope");
   1.406 +        }
   1.407 +    }
   1.408 +    /**
   1.409 +     * Gets the Attributes that are not namesapce declarations
   1.410 +     * @param attrs
   1.411 +     * @return
   1.412 +     */
   1.413 +    private AttributesImpl getAttributes(NamedNodeMap attrs) {
   1.414 +        AttributesImpl atts = new AttributesImpl();
   1.415 +        if(attrs == null)
   1.416 +            return EMPTY_ATTS;
   1.417 +        for(int i=0; i < attrs.getLength();i++) {
   1.418 +            Attr a = (Attr)attrs.item(i);
   1.419 +            //check if attr is ns declaration
   1.420 +            if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
   1.421 +              continue;
   1.422 +            }
   1.423 +            atts.addAttribute(fixNull(a.getNamespaceURI()),a.getLocalName(),a.getName(),a.getSchemaTypeInfo().getTypeName(),a.getValue());
   1.424 +        }
   1.425 +        return atts;
   1.426 +    }
   1.427 +
   1.428 +    /**
   1.429 +     * Collects the ns declarations and starts the prefix mapping, consequently the associated endPrefixMapping needs to be called.
   1.430 +     * @param contentHandler
   1.431 +     * @param attrs
   1.432 +     * @param excludePrefix , this is to excldue the global prefix mapping "S" used at the start
   1.433 +     * @throws SAXException
   1.434 +     */
   1.435 +    private void startPrefixMapping(ContentHandler contentHandler, NamedNodeMap attrs, String excludePrefix) throws SAXException {
   1.436 +        if(attrs == null)
   1.437 +            return;
   1.438 +        for(int i=0; i < attrs.getLength();i++) {
   1.439 +            Attr a = (Attr)attrs.item(i);
   1.440 +            //check if attr is ns declaration
   1.441 +            if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
   1.442 +                if(!fixNull(a.getPrefix()).equals(excludePrefix)) {
   1.443 +                    contentHandler.startPrefixMapping(fixNull(a.getPrefix()), a.getNamespaceURI());
   1.444 +                }
   1.445 +            }
   1.446 +        }
   1.447 +    }
   1.448 +
   1.449 +    private void endPrefixMapping(ContentHandler contentHandler, NamedNodeMap attrs, String excludePrefix) throws SAXException {
   1.450 +        if(attrs == null)
   1.451 +            return;
   1.452 +        for(int i=0; i < attrs.getLength();i++) {
   1.453 +            Attr a = (Attr)attrs.item(i);
   1.454 +            //check if attr is ns declaration
   1.455 +            if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
   1.456 +                if(!fixNull(a.getPrefix()).equals(excludePrefix)) {
   1.457 +                    contentHandler.endPrefixMapping(fixNull(a.getPrefix()));
   1.458 +                }
   1.459 +            }
   1.460 +        }
   1.461 +    }
   1.462 +
   1.463 +    private static String fixNull(String s) {
   1.464 +        if(s==null) return "";
   1.465 +        else        return s;
   1.466 +    }
   1.467 +
   1.468 +    private void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
   1.469 +        if(fragment)
   1.470 +            contentHandler = new FragmentContentHandler(contentHandler);
   1.471 +        DOMScanner ds = new DOMScanner();
   1.472 +        ds.setContentHandler(contentHandler);
   1.473 +        ds.scan(payload);
   1.474 +    }
   1.475 +
   1.476 +    /**
   1.477 +     * Creates a copy of a {@link com.sun.xml.internal.ws.api.message.Message}.
   1.478 +     * <p/>
   1.479 +     * <p/>
   1.480 +     * This method creates a new {@link com.sun.xml.internal.ws.api.message.Message} whose header/payload/attachments/properties
   1.481 +     * are identical to this {@link com.sun.xml.internal.ws.api.message.Message}. Once created, the created {@link com.sun.xml.internal.ws.api.message.Message}
   1.482 +     * and the original {@link com.sun.xml.internal.ws.api.message.Message} behaves independently --- adding header/
   1.483 +     * attachment to one {@link com.sun.xml.internal.ws.api.message.Message} doesn't affect another {@link com.sun.xml.internal.ws.api.message.Message}
   1.484 +     * at all.
   1.485 +     * <p/>
   1.486 +     * <h3>Design Rationale</h3>
   1.487 +     * <p/>
   1.488 +     * Since a {@link com.sun.xml.internal.ws.api.message.Message} body is read-once, sometimes
   1.489 +     * (such as when you do fail-over, or WS-RM) you need to
   1.490 +     * create an idential copy of a {@link com.sun.xml.internal.ws.api.message.Message}.
   1.491 +     * <p/>
   1.492 +     * <p/>
   1.493 +     * The actual copy operation depends on the layout
   1.494 +     * of the data in memory, hence it's best to be done by
   1.495 +     * the {@link com.sun.xml.internal.ws.api.message.Message} implementation itself.
   1.496 +     */
   1.497 +    public Message copy() {
   1.498 +        try {
   1.499 +            if (!parsedMessage) {
   1.500 +                return new SAAJMessage(readAsSOAPMessage());
   1.501 +            } else {
   1.502 +                SOAPMessage msg = soapVersion.getMessageFactory().createMessage();
   1.503 +                SOAPBody newBody = msg.getSOAPPart().getEnvelope().getBody();
   1.504 +                for (Element part : bodyParts) {
   1.505 +                    Node n = newBody.getOwnerDocument().importNode(part, true);
   1.506 +                    newBody.appendChild(n);
   1.507 +                }
   1.508 +                addAttributes(newBody, bodyAttrs);
   1.509 +                return new SAAJMessage(getHeaders(), getAttachments(), msg, soapVersion);
   1.510 +            }
   1.511 +        } catch (SOAPException e) {
   1.512 +            throw new WebServiceException(e);
   1.513 +        }
   1.514 +    }
   1.515 +    private static final AttributesImpl EMPTY_ATTS = new AttributesImpl();
   1.516 +    private static final LocatorImpl NULL_LOCATOR = new LocatorImpl();
   1.517 +
   1.518 +    protected static class SAAJAttachment implements AttachmentEx {
   1.519 +
   1.520 +        final AttachmentPart ap;
   1.521 +
   1.522 +        String contentIdNoAngleBracket;
   1.523 +
   1.524 +        public SAAJAttachment(AttachmentPart part) {
   1.525 +            this.ap = part;
   1.526 +        }
   1.527 +
   1.528 +        /**
   1.529 +         * Content ID of the attachment. Uniquely identifies an attachment.
   1.530 +         */
   1.531 +        public String getContentId() {
   1.532 +            if (contentIdNoAngleBracket == null) {
   1.533 +                contentIdNoAngleBracket = ap.getContentId();
   1.534 +                if (contentIdNoAngleBracket != null && contentIdNoAngleBracket.charAt(0) == '<')
   1.535 +                    contentIdNoAngleBracket = contentIdNoAngleBracket.substring(1, contentIdNoAngleBracket.length()-1);
   1.536 +            }
   1.537 +            return contentIdNoAngleBracket;
   1.538 +        }
   1.539 +
   1.540 +        /**
   1.541 +         * Gets the MIME content-type of this attachment.
   1.542 +         */
   1.543 +        public String getContentType() {
   1.544 +            return ap.getContentType();
   1.545 +        }
   1.546 +
   1.547 +        /**
   1.548 +         * Gets the attachment as an exact-length byte array.
   1.549 +         */
   1.550 +        public byte[] asByteArray() {
   1.551 +            try {
   1.552 +                return ap.getRawContentBytes();
   1.553 +            } catch (SOAPException e) {
   1.554 +                throw new WebServiceException(e);
   1.555 +            }
   1.556 +        }
   1.557 +
   1.558 +        /**
   1.559 +         * Gets the attachment as a {@link javax.activation.DataHandler}.
   1.560 +         */
   1.561 +        public DataHandler asDataHandler() {
   1.562 +            try {
   1.563 +                return ap.getDataHandler();
   1.564 +            } catch (SOAPException e) {
   1.565 +                throw new WebServiceException(e);
   1.566 +            }
   1.567 +        }
   1.568 +
   1.569 +        /**
   1.570 +         * Gets the attachment as a {@link javax.xml.transform.Source}.
   1.571 +         * Note that there's no guarantee that the attachment is actually an XML.
   1.572 +         */
   1.573 +        public Source asSource() {
   1.574 +            try {
   1.575 +                return new StreamSource(ap.getRawContent());
   1.576 +            } catch (SOAPException e) {
   1.577 +                throw new WebServiceException(e);
   1.578 +            }
   1.579 +        }
   1.580 +
   1.581 +        /**
   1.582 +         * Obtains this attachment as an {@link java.io.InputStream}.
   1.583 +         */
   1.584 +        public InputStream asInputStream() {
   1.585 +            try {
   1.586 +                return ap.getRawContent();
   1.587 +            } catch (SOAPException e) {
   1.588 +                throw new WebServiceException(e);
   1.589 +            }
   1.590 +        }
   1.591 +
   1.592 +        /**
   1.593 +         * Writes the contents of the attachment into the given stream.
   1.594 +         */
   1.595 +        public void writeTo(OutputStream os) throws IOException {
   1.596 +            try {
   1.597 +                ASCIIUtility.copyStream(ap.getRawContent(), os);
   1.598 +            } catch (SOAPException e) {
   1.599 +                throw new WebServiceException(e);
   1.600 +            }
   1.601 +        }
   1.602 +
   1.603 +        /**
   1.604 +         * Writes this attachment to the given {@link javax.xml.soap.SOAPMessage}.
   1.605 +         */
   1.606 +        public void writeTo(SOAPMessage saaj) {
   1.607 +            saaj.addAttachmentPart(ap);
   1.608 +        }
   1.609 +
   1.610 +        AttachmentPart asAttachmentPart(){
   1.611 +            return ap;
   1.612 +        }
   1.613 +
   1.614 +                public Iterator<MimeHeader> getMimeHeaders() {
   1.615 +                        final Iterator it = ap.getAllMimeHeaders();
   1.616 +                        return new Iterator<MimeHeader>() {
   1.617 +                                public boolean hasNext() {
   1.618 +                                        return it.hasNext();
   1.619 +                                }
   1.620 +
   1.621 +                                public MimeHeader next() {
   1.622 +                                        final javax.xml.soap.MimeHeader mh = (javax.xml.soap.MimeHeader) it.next();
   1.623 +                                        return new MimeHeader() {
   1.624 +                                                public String getName() {
   1.625 +                                                        return mh.getName();
   1.626 +                                                }
   1.627 +
   1.628 +                                                public String getValue() {
   1.629 +                                                        return mh.getValue();
   1.630 +                                                }
   1.631 +                                        };
   1.632 +                                }
   1.633 +
   1.634 +                                public void remove() {
   1.635 +                                        throw new UnsupportedOperationException();
   1.636 +                                }
   1.637 +                        };
   1.638 +                }
   1.639 +    }
   1.640 +
   1.641 +    /**
   1.642 +     * {@link AttachmentSet} for SAAJ.
   1.643 +     *
   1.644 +     * SAAJ wants '&lt;' and '>' for the content ID, but {@link AttachmentSet}
   1.645 +     * doesn't. S this class also does the conversion between them.
   1.646 +     */
   1.647 +    protected static class SAAJAttachmentSet implements AttachmentSet {
   1.648 +
   1.649 +        private Map<String, Attachment> attMap;
   1.650 +        private Iterator attIter;
   1.651 +
   1.652 +        public SAAJAttachmentSet(SOAPMessage sm) {
   1.653 +            attIter = sm.getAttachments();
   1.654 +        }
   1.655 +
   1.656 +        /**
   1.657 +         * Gets the attachment by the content ID.
   1.658 +         *
   1.659 +         * @return null
   1.660 +         *         if no such attachment exist.
   1.661 +         */
   1.662 +        public Attachment get(String contentId) {
   1.663 +            // if this is the first time then create the attachment Map
   1.664 +            if (attMap == null) {
   1.665 +                if (!attIter.hasNext())
   1.666 +                    return null;
   1.667 +                attMap = createAttachmentMap();
   1.668 +            }
   1.669 +            if(contentId.charAt(0) != '<'){
   1.670 +                return attMap.get('<'+contentId+'>');
   1.671 +            }
   1.672 +            return attMap.get(contentId);
   1.673 +        }
   1.674 +
   1.675 +        public boolean isEmpty() {
   1.676 +            if(attMap!=null)
   1.677 +                return attMap.isEmpty();
   1.678 +            else
   1.679 +                return !attIter.hasNext();
   1.680 +        }
   1.681 +
   1.682 +        /**
   1.683 +         * Returns an iterator over a set of elements of type T.
   1.684 +         *
   1.685 +         * @return an Iterator.
   1.686 +         */
   1.687 +        public Iterator<Attachment> iterator() {
   1.688 +            if (attMap == null) {
   1.689 +                attMap = createAttachmentMap();
   1.690 +            }
   1.691 +            return attMap.values().iterator();
   1.692 +        }
   1.693 +
   1.694 +        private Map<String, Attachment> createAttachmentMap() {
   1.695 +            HashMap<String, Attachment> map = new HashMap<String, Attachment>();
   1.696 +            while (attIter.hasNext()) {
   1.697 +                AttachmentPart ap = (AttachmentPart) attIter.next();
   1.698 +                map.put(ap.getContentId(), new SAAJAttachment(ap));
   1.699 +            }
   1.700 +            return map;
   1.701 +        }
   1.702 +
   1.703 +        public void add(Attachment att) {
   1.704 +            attMap.put('<'+att.getContentId()+'>', att);
   1.705 +        }
   1.706 +    }
   1.707 +
   1.708 +    public SOAPVersion getSOAPVersion() {
   1.709 +        return soapVersion;
   1.710 +    }
   1.711 +
   1.712 +    private XMLStreamReader soapBodyFirstChildReader;
   1.713 +
   1.714 +    /**
   1.715 +     * This allow the subclass to retain the XMLStreamReader.
   1.716 +     */
   1.717 +    protected XMLStreamReader getXMLStreamReader(SOAPElement soapElement) {
   1.718 +        return null;
   1.719 +    }
   1.720 +
   1.721 +    protected XMLStreamReader createXMLStreamReader(SOAPElement soapElement) {
   1.722 +        DOMStreamReader dss = new DOMStreamReader();
   1.723 +        dss.setCurrentNode(soapElement);
   1.724 +        return dss;
   1.725 +    }
   1.726 +
   1.727 +    protected XMLStreamReader soapBodyFirstChildReader() {
   1.728 +        if (soapBodyFirstChildReader != null) return soapBodyFirstChildReader;
   1.729 +        soapBodyFirstChild();
   1.730 +        if (soapBodyFirstChild != null) {
   1.731 +            soapBodyFirstChildReader = getXMLStreamReader(soapBodyFirstChild);
   1.732 +            if (soapBodyFirstChildReader == null) soapBodyFirstChildReader =
   1.733 +                createXMLStreamReader(soapBodyFirstChild);
   1.734 +            if (soapBodyFirstChildReader.getEventType() == XMLStreamReader.START_DOCUMENT) {
   1.735 +                try {
   1.736 +                    while(soapBodyFirstChildReader.getEventType() != XMLStreamReader.START_ELEMENT)
   1.737 +                        soapBodyFirstChildReader.next();
   1.738 +                } catch (XMLStreamException e) {
   1.739 +                    throw new RuntimeException(e);
   1.740 +                }
   1.741 +            }
   1.742 +            return soapBodyFirstChildReader;
   1.743 +        } else {
   1.744 +            payloadLocalName = null;
   1.745 +            payloadNamespace = null;
   1.746 +            return null;
   1.747 +        }
   1.748 +    }
   1.749 +
   1.750 +    private SOAPElement soapBodyFirstChild;
   1.751 +
   1.752 +    SOAPElement soapBodyFirstChild() {
   1.753 +        if (soapBodyFirstChild != null) return soapBodyFirstChild;
   1.754 +        try {
   1.755 +            boolean foundElement = false;
   1.756 +            for (Node n = sm.getSOAPBody().getFirstChild(); n != null && !foundElement; n = n.getNextSibling()) {
   1.757 +                if (n.getNodeType() == Node.ELEMENT_NODE) {
   1.758 +                    foundElement = true;
   1.759 +                    if (n instanceof SOAPElement) {
   1.760 +                        soapBodyFirstChild = (SOAPElement) n;
   1.761 +                        payloadLocalName = soapBodyFirstChild.getLocalName();
   1.762 +                        payloadNamespace = soapBodyFirstChild.getNamespaceURI();
   1.763 +                        return soapBodyFirstChild;
   1.764 +                    }
   1.765 +                }
   1.766 +            }
   1.767 +            if(foundElement) for(Iterator i = sm.getSOAPBody().getChildElements(); i.hasNext();){
   1.768 +                Object o = i.next();
   1.769 +                if (o instanceof SOAPElement) {
   1.770 +                    soapBodyFirstChild = (SOAPElement)o;
   1.771 +                    payloadLocalName = soapBodyFirstChild.getLocalName();
   1.772 +                    payloadNamespace = soapBodyFirstChild.getNamespaceURI();
   1.773 +                    return soapBodyFirstChild;
   1.774 +                }
   1.775 +            }
   1.776 +        } catch (SOAPException e) {
   1.777 +            throw new RuntimeException(e);
   1.778 +        }
   1.779 +        return soapBodyFirstChild;
   1.780 +    }
   1.781 +}

mercurial