Example usage for javax.xml.soap MimeHeaders getHeader

List of usage examples for javax.xml.soap MimeHeaders getHeader

Introduction

In this page you can find the example usage for javax.xml.soap MimeHeaders getHeader.

Prototype

public String[] getHeader(String name) 

Source Link

Document

Returns all of the values for the specified header as an array of String objects.

Usage

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

private void cacheSessionId(SOAPMessage message) {
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    String[] header = mimeHeaders.getHeader("Set-Cookie");
    if (header != null) {
        for (int i = 0; i < header.length; i++) {
            if (header[i].startsWith("JSESSIONID")) {
                // parse JSESSIONID attribute
                String[] attributes = header[i].split(";");
                // JSESSIONID will be first attribute
                credentialInfo.sessionId = attributes[0];
                break;
            }/*from w w w.j  av a2 s.  c om*/
        }
    }
}

From source file:eu.europeana.uim.sugarcrmclient.internal.ExtendedSaajSoapMessageFactory.java

public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
    MimeHeaders mimeHeaders = parseMimeHeaders(inputStream);

    try {/*from  www  .java 2 s.  com*/
        inputStream = checkForUtf8ByteOrderMark(inputStream);
        inputStream = decompressStream((PushbackInputStream) inputStream);
        return new SaajSoapMessage(getMessageFactory().createMessage(mimeHeaders, inputStream));
    } catch (SOAPException ex) {
        // SAAJ 1.3 RI has a issue with handling multipart XOP content types which contain "startinfo" rather than
        // "start-info", so let's try and do something about it
        String contentType = StringUtils
                .arrayToCommaDelimitedString(mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE));
        if (contentType.indexOf("startinfo") != -1) {
            contentType = contentType.replace("startinfo", "start-info");
            mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType);
            try {
                return new SaajSoapMessage(getMessageFactory().createMessage(mimeHeaders, inputStream), true);
            } catch (SOAPException e) {
                // fall-through
            }
        }
        throw new SoapMessageCreationException("Could not create message from InputStream: " + ex.getMessage(),
                ex);
    }
}

From source file:com.hp.it.spf.wsrp.axis.transport.http.HTTPSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context/*from   ww  w  . j a v  a  2s.c  o  m*/
 * @param targetURL url to connect to
 * @param otherHeaders other headers if any
 * @param useFullURL flag to indicate if the whole url needs to be sent
 *
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL targetURL,
        StringBuffer otherHeaders, int timeout, BooleanHolder useFullURL) throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (targetURL.getUserInfo() != null)) {
        String info = targetURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer();

        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE, otherHeaders);
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE2, otherHeaders);
    }

    StringBuffer header2 = new StringBuffer();

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; //True if this is to use HTTP 1.0 / false HTTP 1.1
    boolean httpChunkStream = false; //Use HTTP chunking or not.
    boolean httpContinueExpected = false; //Under HTTP 1.1 if false you *MAY* need to wait for a 100 rc,
                                          //  if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    //process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj)
                continue;
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED))
                        httpChunkStream = true;
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE))
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                }
                //HTTP 1.0 will always close.
                //HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue))
                        httpContinueExpected = true;
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        //Force close for now.
        //TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        final String[] header = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (header != null && header.length > 0) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }

        //fix for AXIS-2027
        if (contentType == null || contentType.equals("")) {
            throw new Exception(Messages.getMessage("missingContentType"));
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    //Get host and port
    String host = targetURL.getHost();
    int port = targetURL.getPort();

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST) //used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION) //The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            //Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            //Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        //Add other headers to the end.
        //for pre java1.4 support, we have to turn the string buffer argument into
        //a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); //The empty line to start the BODY.

    StringBuffer header = new StringBuffer();

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(targetURL.toExternalForm());
    } else {
        header.append((((targetURL.getFile() == null) || targetURL.getFile().equals("")) ? "/"
                : targetURL.getFile()));
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { //We need to get a reply from the server as to whether
        // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
            //Need todo a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { //If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        // Flush ONLY once.
        out.flush();
    }
    if (log.isDebugEnabled()) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}

From source file:org.apache.axis.transport.http.HTTPSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context//from   ww  w . j  a  v a  2 s .  com
 * @param tmpURL url to connect to
 * @param otherHeaders other headers if any
 * @param host host name
 * @param port port
 * @param useFullURL flag to indicate if the whole url needs to be sent
 *
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL tmpURL,
        StringBuffer otherHeaders, String host, int port, int timeout, BooleanHolder useFullURL)
        throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer();

        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE, otherHeaders);
        fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE2, otherHeaders);
    }

    StringBuffer header2 = new StringBuffer();

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; //True if this is to use HTTP 1.0 / false HTTP 1.1
    boolean httpChunkStream = false; //Use HTTP chunking or not.
    boolean httpContinueExpected = false; //Under HTTP 1.1 if false you *MAY* need to wait for a 100 rc,
                                          //  if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    //process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj)
                continue;
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED))
                        httpChunkStream = true;
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE))
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                }
                //HTTP 1.0 will always close.
                //HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue))
                        httpContinueExpected = true;
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        //Force close for now.
        //TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        final String[] header = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (header != null && header.length > 0) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }

        //fix for AXIS-2027
        if (contentType == null || contentType.equals("")) {
            throw new Exception(Messages.getMessage("missingContentType"));
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST) //used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION) //The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            //Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            //Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        //Add other headers to the end.
        //for pre java1.4 support, we have to turn the string buffer argument into
        //a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); //The empty line to start the BODY.

    StringBuffer header = new StringBuffer();

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(tmpURL.toExternalForm());
    } else {
        header.append((((tmpURL.getFile() == null) || tmpURL.getFile().equals("")) ? "/" : tmpURL.getFile()));
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { //We need to get a reply from the server as to whether
        // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
            //Need todo a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { //If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        // Flush ONLY once.
        out.flush();
    }
    if (log.isDebugEnabled()) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}

From source file:org.apache.axis2.saaj.SOAPPartImpl.java

/**
 * Construct a SOAP part from the given input stream.
 * The content type (as provided by the MIME headers) must be SOAP 1.1, SOAP 1.2
 * or XOP (MTOM). MIME packages (multipart/related) are not supported and should be
 * parsed using {@link SOAPMessageImpl#SOAPMessageImpl(InputStream, MimeHeaders).
 * <p>/*from  w  w w.  j a v  a2s. co m*/
 * If the content type is XOP, xop:Include elements will only be replaced if
 * the <code>attachments</code> parameter is not null.
 *
 * @see MessageFactoryImpl#setProcessMTOM(boolean)
 * 
 * @param parentSoapMsg the parent SOAP message
 * @param inputStream the input stream with the content of the SOAP part
 * @param mimeHeaders the MIME headers
 * @param attachments the set of attachments to be used to substitute xop:Include elements
 * @throws SOAPException
 */
public SOAPPartImpl(SOAPMessageImpl parentSoapMsg, InputStream inputStream, MimeHeaders mimeHeaders,
        Attachments attachments) throws SOAPException {
    ContentType contentType = null;
    if (mimeHeaders == null) {
        //TODO : read string from constants
        this.mimeHeaders = new MimeHeaders();
        this.mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
        this.mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
    } else {
        String contentTypes[] = mimeHeaders.getHeader(HTTPConstants.CONTENT_TYPE);
        if (contentTypes != null && contentTypes.length > 0) {
            try {
                contentType = new ContentType(contentTypes[0]);
            } catch (ParseException ex) {
                throw new SOAPException("Invalid content type '" + contentTypes[0] + "'");
            }
        }
        this.mimeHeaders = SAAJUtil.copyMimeHeaders(mimeHeaders);
    }

    soapMessage = parentSoapMsg;

    String charset;
    boolean isMTOM;
    String soapEnvelopeNamespaceURI;
    SOAPFactory soapFactory;
    if (contentType == null) {
        charset = null;
        isMTOM = false;
        soapFactory = new SOAP11Factory();
        soapEnvelopeNamespaceURI = null;
    } else {
        String baseType = contentType.getBaseType().toLowerCase();
        String soapContentType;
        if (baseType.equals(MTOMConstants.MTOM_TYPE)) {
            isMTOM = true;
            String typeParam = contentType.getParameter("type");
            if (typeParam == null) {
                throw new SOAPException("Missing 'type' parameter in XOP content type");
            } else {
                soapContentType = typeParam.toLowerCase();
            }
        } else {
            isMTOM = false;
            soapContentType = baseType;
        }

        if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_TEXT_XML)) {
            soapEnvelopeNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP11Factory();
        } else if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML)) {
            soapEnvelopeNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP12Factory();
        } else {
            throw new SOAPException("Unrecognized content type '" + soapContentType + "'");
        }

        charset = contentType.getParameter("charset");
    }

    XMLStreamReader streamReader;
    try {
        if (charset != null) {
            streamReader = StAXUtils.createXMLStreamReader(inputStream, charset);
        } else {
            streamReader = StAXUtils.createXMLStreamReader(inputStream);
        }
    } catch (XMLStreamException e) {
        throw new SOAPException(e);
    }

    StAXSOAPModelBuilder builder;
    if (isMTOM && attachments != null) {
        builder = new MTOMStAXSOAPModelBuilder(streamReader, soapFactory, attachments,
                soapEnvelopeNamespaceURI);
    } else {
        builder = new StAXSOAPModelBuilder(streamReader, soapFactory, soapEnvelopeNamespaceURI);
    }

    try {
        org.apache.axiom.soap.SOAPEnvelope soapEnvelope = builder.getSOAPEnvelope();
        envelope = new SOAPEnvelopeImpl((org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl) soapEnvelope);
        envelope.element.build();
        this.document = envelope.getOwnerDocument();
        envelope.setSOAPPartParent(this);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}

From source file:org.mule.transport.soap.axis.extensions.MuleHttpSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context//from ww  w.  ja  va2s .c  om
 * @param tmpURL url to connect to
 * @param otherHeaders other headers if any
 * @param host host name
 * @param port port
 * @param useFullURL flag to indicate if the whole url needs to be sent
 * @throws IOException
 */
private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL tmpURL,
        StringBuffer otherHeaders, String host, int port, int timeout, BooleanHolder useFullURL)
        throws Exception {

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        StringBuffer tmpBuf = new StringBuffer(64);
        tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ")
                .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n");
    }

    // don't forget the cookies!
    // mmm... cookies
    if (msgContext.getMaintainSession()) {
        String cookie = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE);
        String cookie2 = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE2);

        if (cookie != null) {
            otherHeaders.append(HTTPConstants.HEADER_COOKIE).append(": ").append(cookie).append("\r\n");
        }
        if (cookie2 != null) {
            otherHeaders.append(HTTPConstants.HEADER_COOKIE2).append(": ").append(cookie2).append("\r\n");
        }
    }

    StringBuffer header2 = new StringBuffer(64);

    String webMethod = null;
    boolean posting = true;

    Message reqMessage = msgContext.getRequestMessage();

    boolean http10 = true; // True if this is to use HTTP 1.0 / false HTTP
    // 1.1
    boolean httpChunkStream = false; // Use HTTP chunking or not.
    boolean httpContinueExpected = false; // Under HTTP 1.1 if false you
    // *MAY* need to wait for a 100
    // rc,
    // if true the server MUST reply with 100 continue.
    String httpConnection = null;

    String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (null == httpver) {
        httpver = HTTPConstants.HEADER_PROTOCOL_V10;
    }
    httpver = httpver.trim();
    if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
        http10 = false;
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        if (null == otherHeaders) {
            otherHeaders = new StringBuffer(1024);
        }

        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {

            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();
            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (null != val
                            && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                        httpChunkStream = true;
                    }
                }
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
                if (!http10) {
                    String val = me.getValue().toString();
                    if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE)) {
                        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
                    }
                }
                // HTTP 1.0 will always close.
                // HTTP 1.1 will use persistent. //no need to specify
            } else {
                if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    String val = me.getValue().toString();
                    if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                        httpContinueExpected = true;
                    }
                }

                otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
            }
        }
    }

    if (!http10) {
        // Force close for now.
        // TODO HTTP/1.1
        httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
    }

    header2.append(" ");
    header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n");
    MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();

    if (posting) {
        String contentType;
        if (mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
        } else {
            contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
        }
        header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n");
    }

    header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST)
            // used for virtual connections
            .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n")
            .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION)
            // The SOAP action.
            .append(": \"").append(action).append("\"\r\n");

    if (posting) {
        if (!httpChunkStream) {
            // Content length MUST be sent on HTTP 1.0 requests.
            header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ")
                    .append(reqMessage.getContentLength()).append("\r\n");
        } else {
            // Do http chunking.
            header2.append(CHUNKED_HEADER);
        }
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n");
        }
    }

    if (null != httpConnection) {
        header2.append(HTTPConstants.HEADER_CONNECTION);
        header2.append(": ");
        header2.append(httpConnection);
        header2.append("\r\n");
    }

    getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL);

    if (null != otherHeaders) {
        // Add other headers to the end.
        // for pre java1.4 support, we have to turn the string buffer
        // argument into
        // a string before appending.
        header2.append(otherHeaders.toString());
    }

    header2.append("\r\n"); // The empty line to start the BODY.

    StringBuffer header = new StringBuffer(128);

    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
    }
    if (webMethod == null) {
        webMethod = HTTPConstants.HEADER_POST;
    } else {
        posting = webMethod.equals(HTTPConstants.HEADER_POST);
    }

    header.append(webMethod).append(" ");
    if (useFullURL.value) {
        header.append(tmpURL.toExternalForm());
    } else {
        header.append(StringUtils.isEmpty(tmpURL.getFile()) ? "/" : tmpURL.getFile());
    }
    header.append(header2.toString());

    OutputStream out = sockHolder.getSocket().getOutputStream();

    if (!posting) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
        out.flush();
        return null;
    }

    InputStream inp = null;

    if (httpChunkStream || httpContinueExpected) {
        out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
    }

    if (httpContinueExpected) { // We need to get a reply from the server as
                                // to whether
                                // it wants us send anything more.
        out.flush();
        Hashtable cheaders = new Hashtable();
        inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
        int returnCode = -1;
        Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        if (null != Irc) {
            returnCode = Irc.intValue();
        }
        if (100 == returnCode) { // got 100 we may continue.
                                 // Need TODO a little msgContext house keeping....
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
            msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        } else { // If no 100 Continue then we must not send anything!
            String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            fault.setFaultDetailString(Messages.getMessage("return01", String.valueOf(returnCode), ""));
            throw fault;
        }
    }
    ByteArrayOutputStream baos = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("xmlSent00"));
        log.debug("---------------------------------------------------");
        baos = new ByteArrayOutputStream();
    }
    if (httpChunkStream) {
        ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
        out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            log.error(Messages.getMessage("exception00"), e);
        }
        out.flush();
        chunkedOutputStream.eos();
    } else {
        out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
        try {
            if (!httpContinueExpected) {
                out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
            }
            if (baos != null) {
                out = new TeeOutputStream(out, baos);
            }
            reqMessage.writeTo(out);
        } catch (SOAPException e) {
            throw e;
        } finally {
            // Flush ONLY once.
            out.flush();
        }

    }

    if (log.isDebugEnabled() && baos != null) {
        log.debug(header + new String(baos.toByteArray()));
    }

    return inp;
}

From source file:org.springframework.ws.soap.saaj.SaajSoapMessageFactory.java

public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
    MimeHeaders mimeHeaders = parseMimeHeaders(inputStream);
    try {//w  w  w.j a v a  2s .  c  o  m
        inputStream = checkForUtf8ByteOrderMark(inputStream);
        SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream);
        postProcess(saajMessage);
        return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory);
    } catch (SOAPException ex) {
        // SAAJ 1.3 RI has a issue with handling multipart XOP content types which contain "startinfo" rather than
        // "start-info", so let's try and do something about it
        String contentType = StringUtils
                .arrayToCommaDelimitedString(mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE));
        if (contentType.contains("startinfo")) {
            contentType = contentType.replace("startinfo", "start-info");
            mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType);
            try {
                SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream);
                postProcess(saajMessage);
                return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString);
            } catch (SOAPException e) {
                // fall-through
            }
        }
        throw new SoapMessageCreationException("Could not create message from InputStream: " + ex.getMessage(),
                ex);
    } catch (SaajSoapEnvelopeException ex) {
        SAXParseException parseException = getSAXParseException(ex);
        if (parseException != null) {
            throw new InvalidXmlException("Could not parse XML", parseException);
        } else {
            throw ex;
        }
    }
}

From source file:test.saaj.TestAttachmentSerialization.java

public int saveMsgWithAttachments(OutputStream os) throws Exception {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage();

    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();

    SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
    SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
    SOAPElement el3 = el2.addTextNode("field4value");

    el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
    el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
    el2.addTextNode("bodyvalue3a");
    el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
    el2.addTextNode("bodyvalue3b");
    el2 = el.addChildElement("datefield", NS_PREFIX);

    AttachmentPart ap = msg.createAttachmentPart();
    ap.setContent("some attachment text...", "text/plain");
    msg.addAttachmentPart(ap);//from   ww w.  j a v  a 2 s  .co  m

    String jpgfilename = "docs/images/axis.jpg";
    File myfile = new File(jpgfilename);
    FileDataSource fds = new FileDataSource(myfile);
    DataHandler dh = new DataHandler(fds);
    AttachmentPart ap2 = msg.createAttachmentPart(dh);
    ap2.setContentType("image/jpg");
    msg.addAttachmentPart(ap2);

    // Test for Bug #17664
    if (msg.saveRequired()) {
        msg.saveChanges();
    }
    MimeHeaders headers = msg.getMimeHeaders();
    assertTrue(headers != null);
    String[] contentType = headers.getHeader("Content-Type");
    assertTrue(contentType != null);

    msg.writeTo(os);
    os.flush();
    return msg.countAttachments();
}