Example usage for javax.xml.soap MimeHeaders getAllHeaders

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

Introduction

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

Prototype

public Iterator<MimeHeader> getAllHeaders() 

Source Link

Document

Returns all the MimeHeader s in this MimeHeaders object.

Usage

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  va  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.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * Extracts info from message context./* w ww. ja  v a 2 s  .  co  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception
 * @deprecated
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one
         definition of timeout */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.setTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }
    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // 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) {
        Credentials cred = new UsernamePasswordCredentials(userID, passwd);
        httpClient.getState().setCredentials(null, null, cred);

        // Change #2
        //
        // Comment out the lines below since they force all authentication
        // to be Basic. This is a problem if the web service you're invoking 
        // is expecting Digest.

        // The following 3 lines should NOT be required. But Our SimpleAxisServer fails
        // during all-tests if this is missing.
        //            StringBuffer tmpBuf = new StringBuffer();
        //            tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        //            method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes()));
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

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

    if (userHeaderTable != null) {
        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();
            String value = me.getValue().toString().trim();

            method.addRequestHeader(key, value);
        }
    }
}

From source file:org.apache.axis.attachments.AttachmentPart.java

/**
 * check if this Part's mimeheaders matches the one passed in.
 * TODO: Am not sure about the logic./*  w  ww. j ava  2 s . co m*/
 *
 * @param headers  the <code>MimeHeaders</code> to check
 * @return true if all header name, values in <code>headers</code> are
 *              found, false otherwise
 */
public boolean matches(javax.xml.soap.MimeHeaders headers) {
    for (Iterator i = headers.getAllHeaders(); i.hasNext();) {
        javax.xml.soap.MimeHeader hdr = (javax.xml.soap.MimeHeader) i.next();
        String values[] = mimeHeaders.getHeader(hdr.getName());
        boolean found = false;
        if (values != null) {
            for (int j = 0; j < values.length; j++) {
                if (!hdr.getValue().equalsIgnoreCase(values[j])) {
                    continue;
                }
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }
    return true;
}

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

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request/*from  w  ww.j a  v  a 2 s .c o m*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    if (isDebug) {
        log.debug("Enter: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    Message responseMsg = null;
    String contentType = null;

    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        /* Get request message
         */
        Message requestMsg = new Message(req.getInputStream(), false,
                req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.
        String requestEncoding;
        try {
            requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);

            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }
            responseMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {
            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage()
                        .setMessageContext(msgContext);
            }
        } catch (Exception e) {
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = convertExceptionToAxisFault(e, responseMsg);
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        } catch (Throwable t) {
            logException(t);
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = new Message(new AxisFault(t.toString(), t));
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    /* Send response back along the wire...  */
    /***********************************/
    if (responseMsg != null) {
        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = responseMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }
        //determine content type from message response
        contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
        sendResponse(contentType, res, responseMsg);
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

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

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context//from   w w w. jav a 2s  . c o m
 * @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.axis.transport.http.SimpleAxisWorker.java

/**
 * The main workhorse method.//from  ww  w  . java 2  s  .  c  om
 */
public void execute() {
    byte buf[] = new byte[BUFSIZ];
    // create an Axis server
    AxisServer engine = server.getAxisServer();

    // create and initialize a message context
    MessageContext msgContext = new MessageContext(engine);
    Message requestMsg = null;

    // Reusuable, buffered, content length controlled, InputStream
    NonBlockingBufferedInputStream is = new NonBlockingBufferedInputStream();

    // buffers for the headers we care about
    StringBuffer soapAction = new StringBuffer();
    StringBuffer httpRequest = new StringBuffer();
    StringBuffer fileName = new StringBuffer();
    StringBuffer cookie = new StringBuffer();
    StringBuffer cookie2 = new StringBuffer();
    StringBuffer authInfo = new StringBuffer();
    StringBuffer contentType = new StringBuffer();
    StringBuffer contentLocation = new StringBuffer();

    Message responseMsg = null;

    // prepare request (do as much as possible while waiting for the
    // next connection).  Note the next two statements are commented
    // out.  Uncomment them if you experience any problems with not
    // resetting state between requests:
    //   msgContext = new MessageContext();
    //   requestMsg = new Message("", "String");
    //msgContext.setProperty("transport", "HTTPTransport");
    msgContext.setTransportName(transportName);

    responseMsg = null;

    try {
        // assume the best
        byte[] status = OK;

        // assume we're not getting WSDL
        boolean doWsdl = false;

        // cookie for this session, if any
        String cooky = null;

        String methodName = null;

        try {
            // wipe cookies if we're doing sessions
            if (server.isSessionUsed()) {
                cookie.delete(0, cookie.length());
                cookie2.delete(0, cookie2.length());
            }
            authInfo.delete(0, authInfo.length());

            // read headers
            is.setInputStream(socket.getInputStream());
            // parse all headers into hashtable
            MimeHeaders requestHeaders = new MimeHeaders();
            int contentLength = parseHeaders(is, buf, contentType, contentLocation, soapAction, httpRequest,
                    fileName, cookie, cookie2, authInfo, requestHeaders);
            is.setContentLength(contentLength);

            int paramIdx = fileName.toString().indexOf('?');
            if (paramIdx != -1) {
                // Got params
                String params = fileName.substring(paramIdx + 1);
                fileName.setLength(paramIdx);

                log.debug(Messages.getMessage("filename00", fileName.toString()));
                log.debug(Messages.getMessage("params00", params));

                if ("wsdl".equalsIgnoreCase(params))
                    doWsdl = true;

                if (params.startsWith("method=")) {
                    methodName = params.substring(7);
                }
            }

            // Real and relative paths are the same for the
            // SimpleAxisServer
            msgContext.setProperty(Constants.MC_REALPATH, fileName.toString());
            msgContext.setProperty(Constants.MC_RELATIVE_PATH, fileName.toString());
            msgContext.setProperty(Constants.MC_JWS_CLASSDIR, "jwsClasses");
            msgContext.setProperty(Constants.MC_HOME_DIR, ".");

            // !!! Fix string concatenation
            String url = "http://" + getLocalHost() + ":" + server.getServerSocket().getLocalPort() + "/"
                    + fileName.toString();
            msgContext.setProperty(MessageContext.TRANS_URL, url);

            String filePart = fileName.toString();
            if (filePart.startsWith("axis/services/")) {
                String servicePart = filePart.substring(14);
                int separator = servicePart.indexOf('/');
                if (separator > -1) {
                    msgContext.setProperty("objectID", servicePart.substring(separator + 1));
                    servicePart = servicePart.substring(0, separator);
                }
                msgContext.setTargetService(servicePart);
            }

            if (authInfo.length() > 0) {
                // Process authentication info
                //authInfo = new StringBuffer("dXNlcjE6cGFzczE=");
                byte[] decoded = Base64.decode(authInfo.toString());
                StringBuffer userBuf = new StringBuffer();
                StringBuffer pwBuf = new StringBuffer();
                StringBuffer authBuf = userBuf;
                for (int i = 0; i < decoded.length; i++) {
                    if ((char) (decoded[i] & 0x7f) == ':') {
                        authBuf = pwBuf;
                        continue;
                    }
                    authBuf.append((char) (decoded[i] & 0x7f));
                }

                if (log.isDebugEnabled()) {
                    log.debug(Messages.getMessage("user00", userBuf.toString()));
                }

                msgContext.setUsername(userBuf.toString());
                msgContext.setPassword(pwBuf.toString());
            }

            // if get, then return simpleton document as response
            if (httpRequest.toString().equals("GET")) {

                OutputStream out = socket.getOutputStream();
                out.write(HTTP);
                if (fileName.length() == 0) {
                    out.write("301 Redirect\nLocation: /axis/\n\n".getBytes());
                    out.flush();
                    return;
                }
                out.write(status);

                if (methodName != null) {
                    String body = "<" + methodName + ">" +
                    //                               args +
                            "</" + methodName + ">";
                    String msgtxt = "<SOAP-ENV:Envelope" + " xmlns:SOAP-ENV=\"" + Constants.URI_SOAP12_ENV
                            + "\">" + "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";

                    ByteArrayInputStream istream = new ByteArrayInputStream(msgtxt.getBytes());
                    requestMsg = new Message(istream);
                } else if (doWsdl) {
                    engine.generateWSDL(msgContext);

                    Document doc = (Document) msgContext.getProperty("WSDL");
                    if (doc != null) {
                        XMLUtils.normalize(doc.getDocumentElement());
                        String response = XMLUtils.PrettyDocumentToString(doc);
                        byte[] respBytes = response.getBytes();

                        out.write(XML_MIME_STUFF);
                        putInt(buf, out, respBytes.length);
                        out.write(SEPARATOR);
                        out.write(respBytes);
                        out.flush();
                        return;
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append("<h2>And now... Some Services</h2>\n");
                    Iterator i = engine.getConfig().getDeployedServices();
                    sb.append("<ul>\n");
                    while (i.hasNext()) {
                        ServiceDesc sd = (ServiceDesc) i.next();
                        sb.append("<li>\n");
                        sb.append(sd.getName());
                        sb.append(" <a href=\"services/");
                        sb.append(sd.getName());
                        sb.append("?wsdl\"><i>(wsdl)</i></a></li>\n");
                        ArrayList operations = sd.getOperations();
                        if (!operations.isEmpty()) {
                            sb.append("<ul>\n");
                            for (Iterator it = operations.iterator(); it.hasNext();) {
                                OperationDesc desc = (OperationDesc) it.next();
                                sb.append("<li>" + desc.getName());
                            }
                            sb.append("</ul>\n");
                        }
                    }
                    sb.append("</ul>\n");

                    byte[] bytes = sb.toString().getBytes();

                    out.write(HTML_MIME_STUFF);
                    putInt(buf, out, bytes.length);
                    out.write(SEPARATOR);
                    out.write(bytes);
                    out.flush();
                    return;
                }
            } else {

                // this may be "" if either SOAPAction: "" or if no SOAPAction at all.
                // for now, do not complain if no SOAPAction at all
                String soapActionString = soapAction.toString();
                if (soapActionString != null) {
                    msgContext.setUseSOAPAction(true);
                    msgContext.setSOAPActionURI(soapActionString);
                }
                requestMsg = new Message(is, false, contentType.toString(), contentLocation.toString());
            }

            // Transfer HTTP headers to MIME headers for request message.
            MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
            for (Iterator i = requestHeaders.getAllHeaders(); i.hasNext();) {
                MimeHeader requestHeader = (MimeHeader) i.next();
                requestMimeHeaders.addHeader(requestHeader.getName(), requestHeader.getValue());
            }
            msgContext.setRequestMessage(requestMsg);
            // put character encoding of request to message context
            // in order to reuse it during the whole process.   
            String requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }

            // set up session, if any
            if (server.isSessionUsed()) {
                // did we get a cookie?
                if (cookie.length() > 0) {
                    cooky = cookie.toString().trim();
                } else if (cookie2.length() > 0) {
                    cooky = cookie2.toString().trim();
                }

                // if cooky is null, cook up a cooky
                if (cooky == null) {
                    // fake one up!
                    // make it be an arbitrarily increasing number
                    // (no this is not thread safe because ++ isn't atomic)
                    int i = SimpleAxisServer.sessionIndex++;
                    cooky = "" + i;
                }

                msgContext.setSession(server.createSession(cooky));
            }

            // invoke the Axis engine
            engine.invoke(msgContext);

            // Retrieve the response from Axis
            responseMsg = msgContext.getResponseMessage();

            if (responseMsg == null) {
                status = NOCONTENT;
            }
        } catch (Exception e) {
            AxisFault af;
            if (e instanceof AxisFault) {
                af = (AxisFault) e;
                log.debug(Messages.getMessage("serverFault00"), af);
                QName faultCode = af.getFaultCode();
                if (Constants.FAULT_SOAP12_SENDER.equals(faultCode)) {
                    status = SENDER;
                } else if ("Server.Unauthorized".equals(af.getFaultCode().getLocalPart())) {
                    status = UNAUTH; // SC_UNAUTHORIZED
                } else {
                    status = ISE; // SC_INTERNAL_SERVER_ERROR
                }
            } else {
                status = ISE; // SC_INTERNAL_SERVER_ERROR
                af = AxisFault.makeFault(e);
            }

            // There may be headers we want to preserve in the
            // response message - so if it's there, just add the
            // FaultElement to it.  Otherwise, make a new one.
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(af);
                responseMsg.setMessageContext(msgContext);
            } else {
                try {
                    SOAPEnvelope env = responseMsg.getSOAPEnvelope();
                    env.clearBody();
                    env.addBodyElement(new SOAPFault((AxisFault) e));
                } catch (AxisFault fault) {
                    // Should never reach here!
                }
            }
        }

        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null && responseMsg != null) {
            responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
        }
        // Send it on its way...
        OutputStream out = socket.getOutputStream();
        out.write(HTTP);
        out.write(status);

        if (responseMsg != null) {
            if (server.isSessionUsed() && null != cooky && 0 != cooky.trim().length()) {
                // write cookie headers, if any
                // don't sweat efficiency *too* badly
                // optimize at will
                StringBuffer cookieOut = new StringBuffer();
                cookieOut.append("\r\nSet-Cookie: ").append(cooky).append("\r\nSet-Cookie2: ").append(cooky);
                // OH, THE HUMILITY!  yes this is inefficient.
                out.write(cookieOut.toString().getBytes());
            }

            //out.write(XML_MIME_STUFF);
            out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_TYPE + ": "
                    + responseMsg.getContentType(msgContext.getSOAPConstants())).getBytes());
            // Writing the length causes the entire message to be decoded twice.
            //out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_LENGTH + ": " + responseMsg.getContentLength()).getBytes());
            // putInt(out, response.length);

            // Transfer MIME headers to HTTP headers for response message.
            for (Iterator i = responseMsg.getMimeHeaders().getAllHeaders(); i.hasNext();) {
                MimeHeader responseHeader = (MimeHeader) i.next();
                out.write('\r');
                out.write('\n');
                out.write(responseHeader.getName().getBytes());
                out.write(headerEnder);
                out.write(responseHeader.getValue().getBytes());
            }

            out.write(SEPARATOR);
            responseMsg.writeTo(out);
        }

        // out.write(response);
        out.flush();
    } catch (Exception e) {
        log.info(Messages.getMessage("exception00"), e);
    } finally {
        try {
            if (socket != null)
                socket.close();
        } catch (Exception e) {
        }
    }
    if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
        // why then, quit!
        try {
            server.stop();
        } catch (Exception e) {
        }
    }

}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * Extracts info from message context./*from www .ja  v  a2 s  .  co m*/
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * @throws Exception
 */
protected void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext,
        URL tmpURL) throws Exception {

    // optionally set a timeout for the request
    //      if (msgContext.getTimeout() != 0) {
    //         /* ISSUE: these are not the same, but MessageContext has only one
    //                   definition of timeout */
    //         // SO_TIMEOUT -- timeout for blocking reads
    //         httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
    //         // timeout for initial connection
    //         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    //      }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // 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) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\"); //$NON-NLS-1$
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

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

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes)
                if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) {
                    method.setRequestHeader(key, value);
                } else {
                    method.addRequestHeader(key, value);
                }
            }
        }
    }
}

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

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context// www .j  av a 2 s.  c o m
 * @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;
}