Example usage for javax.xml.soap MimeHeaders addHeader

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

Introduction

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

Prototype

public void addHeader(String name, String value) 

Source Link

Document

Adds a MimeHeader object with the specified name and value to this MimeHeaders object's list of headers.

Usage

From source file:lucee.runtime.net.rpc.server.RPCServer.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//  ww w  .  j a v a 2 s  .  co m
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component)
        throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;

    Message rspMsg = null;
    String contentType = null;
    InputStream is = 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, component);
        ComponentController.set(msgContext);

        // ? 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);
        }

        is = req.getInputStream();
        Message requestMsg = new Message(is, 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().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.

        try {
            String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (reqEnc != null)
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc);
        } 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
            }
            //msgContext.setProperty("disablePrettyXML", "false");
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }

            rspMsg = 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);
            rspMsg = msgContext.getResponseMessage();
            if (rspMsg == null) {
                rspMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = convertExceptionToAxisFault(e, rspMsg);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);

            }
            // throwable
            else {
                logException(t);
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {

        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        rspMsg = msgContext.getResponseMessage();
        if (rspMsg == null) {
            rspMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }

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

    // Send response back along the wire... 
    if (rspMsg != null) {

        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = rspMsg.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 {
                rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }

        //determine content type from message response
        contentType = rspMsg.getContentType(msgContext.getSOAPConstants());
        if (isDebug)
            log.debug("Returned Content-Type:" + contentType);

        // write result to response stream
        try {
            res.setContentType(contentType);
            rspMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }

        if (!res.isCommitted())
            res.flushBuffer(); // Force it right now.
    } 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:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* invoke creates a socket connection, sends the request SOAP message and
* then reads the response SOAP message back from the SOAP server
* 
* @param msgContext//w w  w.j  a  v  a  2s.c om
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke"));
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);

        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

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

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();

            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

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

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the message context
 *
 * @throws AxisFault/*from w ww. j a  v  a  2  s .  c  o  m*/
 * @deprecated
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL);
        httpClient.setHostConfiguration(hostConfiguration);

        // look for option to send credentials preemptively (w/out challenge)
        // Control of Preemptive is controlled via policy on a per call basis.
        String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$
        if ("true".equals(preemptive)) //$NON-NLS-1$
        {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        String webMethod = null;
        boolean posting = true;

        // 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) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        Message reqMessage = msgContext.getRequestMessage();
        if (posting) {
            method = new PostMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            reqMessage.writeTo(baos);
            ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray()));
            ((PostMethod) method).setUseExpectHeader(false); // workaround for
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }
        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE);

            String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2);
            if (ck1 != null) {
                int index = ck1.indexOf('=');
                state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null,
                        secure));
            }
            if (ck2 != null) {
                int index = ck2.indexOf('=');
                state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null,
                        secure));
            }
            httpClient.setState(state);
        }
        boolean hasSoapFault = false;
        int returnCode = httpClient.executeMethod(method);
        String contentType = null;
        String contentLocation = null;
        String contentLength = null;
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) {
            contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) {
            contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue();
        }
        contentType = (null == contentType) ? null : contentType.trim();
        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
            hasSoapFault = true;
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$
                    "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$
                            + statusMessage,
                    null, null);

            try {
                fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$
                        "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }

        OperationDesc operation = msgContext.getOperation();
        if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) {
            msgContext.setResponseMessage(outMsg);
        } else {
            // Change #1
            //
            // If the operation is a one-way, then don't set the response
            // on the msg context. Doing so will cause Axis to attempt to
            // read from a non-existent SOAP message which causes errors.
            //
            // Note: also checking to see if the return type is our "VOID"
            // QName from the AeInvokeHandler since that's our workaround
            // for avoiding Axis's Thread creation in Call.invokeOneWay()
            //
            // Since the message context won't have a chance to consume the
            // response stream (which closes the connection), close the
            // connection here.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" //$NON-NLS-1$
                        + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug("-----------------------------------------------"); //$NON-NLS-1$
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue()));
                else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue()));
            }

        }

    } catch (Throwable t) {
        log.debug(t);

        if (method != null) {
            method.releaseConnection();
        }

        // We can call Axis.makeFault() if it's an exception; otherwise
        // construct the AxisFault directly.
        throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t)
                : new AxisFault(t.getLocalizedMessage(), t);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
}

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  w w. j  a  va2  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.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the messsage context
 *
 * @throws AxisFault/*from  w w  w.  j  a  v a  2s.  c o  m*/
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

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

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase 
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases 
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                throw fault;
            }

        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

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

/**
 * Reads the SOAP response back from the server
 *
 * @param msgContext message context/*from  w w  w .  j  a va2 s . co m*/
 *
 * @throws IOException
 */
private InputStream readFromSocket(SocketHolder socketHolder, MessageContext msgContext, InputStream inp,
        Hashtable headers) throws IOException {
    Message outMsg = null;
    byte b;

    Integer rc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
    int returnCode = 0;
    if (rc != null) {
        returnCode = rc.intValue();
    } else {
        // No return code?? Should have one by now.
    }

    /* All HTTP headers have been read. */
    String contentType = (String) headers.get(HEADER_CONTENT_TYPE_LC);

    contentType = (null == contentType) ? null : contentType.trim();

    String location = (String) headers.get(HEADER_LOCATION_LC);

    location = (null == location) ? null : location.trim();

    if ((returnCode > 199) && (returnCode < 300)) {
        if (returnCode == 202) {
            return inp;
        }
        // SOAP return is OK - so fall through
    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        // For now, if we're SOAP 1.2, fall through, since the range of
        // valid result codes is much greater
    } else if ((contentType != null) && !contentType.startsWith("text/html")
            && ((returnCode > 499) && (returnCode < 600))) {
        // SOAP Fault should be in here - so fall through
    } else if ((location != null) && ((returnCode == 302) || (returnCode == 307))) {
        // Temporary Redirect (HTTP: 302/307)            
        // close old connection
        inp.close();
        socketHolder.getSocket().close();
        // remove former result and set new target url
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        msgContext.setProperty(MessageContext.TRANS_URL, location);
        // next try
        invoke(msgContext);
        return inp;
    } else if (returnCode == 100) {
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        readHeadersFromSocket(socketHolder, msgContext, inp, headers);
        return readFromSocket(socketHolder, msgContext, inp, headers);
    } else {
        // Unknown return code - so wrap up the content into a
        // SOAP Fault.
        ByteArrayOutputStream buf = new ByteArrayOutputStream(4097);

        while (-1 != (b = (byte) inp.read())) {
            buf.write(b);
        }
        String statusMessage = msgContext.getStrProp(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

        fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, buf.toString()));
        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
        throw fault;
    }

    String contentLocation = (String) headers.get(HEADER_CONTENT_LOCATION_LC);

    contentLocation = (null == contentLocation) ? null : contentLocation.trim();

    String contentLength = (String) headers.get(HEADER_CONTENT_LENGTH_LC);

    contentLength = (null == contentLength) ? null : contentLength.trim();

    String transferEncoding = (String) headers.get(HEADER_TRANSFER_ENCODING_LC);

    if (null != transferEncoding) {
        transferEncoding = transferEncoding.trim().toLowerCase();
        if (transferEncoding.equals(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
            inp = new ChunkedInputStream(inp);
        }
    }

    outMsg = new Message(new SocketInputStream(inp, socketHolder.getSocket()), false, contentType,
            contentLocation);
    // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
    MimeHeaders mimeHeaders = outMsg.getMimeHeaders();
    for (Enumeration e = headers.keys(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        mimeHeaders.addHeader(key, ((String) headers.get(key)).trim());
    }
    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        if (null == contentLength) {
            log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
        }
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPEnvelope().toString());
    }

    return inp;
}

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

/**
 * The main workhorse method.//w ww . ja  v a2  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.apache.axis.transport.http.SimpleAxisWorker.java

/**
 * Read all mime headers, returning the value of Content-Length and
 * SOAPAction.//w ww.jav a2  s  .c  om
 * @param is         InputStream to read from
 * @param contentType The content type.
 * @param contentLocation The content location
 * @param soapAction StringBuffer to return the soapAction into
 * @param httpRequest StringBuffer for GET / POST
 * @param cookie first cookie header (if doSessions)
 * @param cookie2 second cookie header (if doSessions)
 * @param headers HTTP headers to transfer to MIME headers
 * @return Content-Length
 */
private int parseHeaders(NonBlockingBufferedInputStream is, byte buf[], StringBuffer contentType,
        StringBuffer contentLocation, StringBuffer soapAction, StringBuffer httpRequest, StringBuffer fileName,
        StringBuffer cookie, StringBuffer cookie2, StringBuffer authInfo, MimeHeaders headers)
        throws java.io.IOException {
    int n;
    int len = 0;

    // parse first line as GET or POST
    n = this.readLine(is, buf, 0, buf.length);
    if (n < 0) {
        // nothing!
        throw new java.io.IOException(Messages.getMessage("unexpectedEOS00"));
    }

    // which does it begin with?
    httpRequest.delete(0, httpRequest.length());
    fileName.delete(0, fileName.length());
    contentType.delete(0, contentType.length());
    contentLocation.delete(0, contentLocation.length());

    if (buf[0] == getHeader[0]) {
        httpRequest.append("GET");
        for (int i = 0; i < n - 5; i++) {
            char c = (char) (buf[i + 5] & 0x7f);
            if (c == ' ')
                break;
            fileName.append(c);
        }
        log.debug(Messages.getMessage("filename01", "SimpleAxisServer", fileName.toString()));
        return 0;
    } else if (buf[0] == postHeader[0]) {
        httpRequest.append("POST");
        for (int i = 0; i < n - 6; i++) {
            char c = (char) (buf[i + 6] & 0x7f);
            if (c == ' ')
                break;
            fileName.append(c);
        }
        log.debug(Messages.getMessage("filename01", "SimpleAxisServer", fileName.toString()));
    } else {
        throw new java.io.IOException(Messages.getMessage("badRequest00"));
    }

    while ((n = readLine(is, buf, 0, buf.length)) > 0) {

        if ((n <= 2) && (buf[0] == '\n' || buf[0] == '\r') && (len > 0))
            break;

        // RobJ gutted the previous logic; it was too hard to extend for more headers.
        // Now, all it does is search forwards for ": " in the buf,
        // then do a length / byte compare.
        // Hopefully this is still somewhat efficient (Sam is watching!).

        // First, search forwards for ": "
        int endHeaderIndex = 0;
        while (endHeaderIndex < n && toLower[buf[endHeaderIndex]] != headerEnder[0]) {
            endHeaderIndex++;
        }
        endHeaderIndex += 2;
        // endHeaderIndex now points _just past_ the ": ", and is
        // comparable to the various lenLen, actionLen, etc. values

        // convenience; i gets pre-incremented, so initialize it to one less
        int i = endHeaderIndex - 1;

        // which header did we find?
        if (endHeaderIndex == lenLen && matches(buf, lenHeader)) {
            // parse content length

            while ((++i < n) && (buf[i] >= '0') && (buf[i] <= '9')) {
                len = (len * 10) + (buf[i] - '0');
            }
            headers.addHeader(HTTPConstants.HEADER_CONTENT_LENGTH, String.valueOf(len));

        } else if (endHeaderIndex == actionLen && matches(buf, actionHeader)) {

            soapAction.delete(0, soapAction.length());
            // skip initial '"'
            i++;
            while ((++i < n) && (buf[i] != '"')) {
                soapAction.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + soapAction.toString() + "\"");

        } else if (server.isSessionUsed() && endHeaderIndex == cookieLen && matches(buf, cookieHeader)) {

            // keep everything up to first ;
            while ((++i < n) && (buf[i] != ';') && (buf[i] != '\r') && (buf[i] != '\n')) {
                cookie.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader("Set-Cookie", cookie.toString());

        } else if (server.isSessionUsed() && endHeaderIndex == cookie2Len && matches(buf, cookie2Header)) {

            // keep everything up to first ;
            while ((++i < n) && (buf[i] != ';') && (buf[i] != '\r') && (buf[i] != '\n')) {
                cookie2.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader("Set-Cookie2", cookie.toString());

        } else if (endHeaderIndex == authLen && matches(buf, authHeader)) {
            if (matches(buf, endHeaderIndex, basicAuth)) {
                i += basicAuth.length;
                while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
                    if (buf[i] == ' ')
                        continue;
                    authInfo.append((char) (buf[i] & 0x7f));
                }
                headers.addHeader(HTTPConstants.HEADER_AUTHORIZATION,
                        new String(basicAuth) + authInfo.toString());
            } else {
                throw new java.io.IOException(Messages.getMessage("badAuth00"));
            }
        } else if (endHeaderIndex == locationLen && matches(buf, locationHeader)) {
            while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
                if (buf[i] == ' ')
                    continue;
                contentLocation.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation.toString());
        } else if (endHeaderIndex == typeLen && matches(buf, typeHeader)) {
            while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
                if (buf[i] == ' ')
                    continue;
                contentType.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentLocation.toString());
        } else {
            String customHeaderName = new String(buf, 0, endHeaderIndex - 2);
            StringBuffer customHeaderValue = new StringBuffer();
            while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
                if (buf[i] == ' ')
                    continue;
                customHeaderValue.append((char) (buf[i] & 0x7f));
            }
            headers.addHeader(customHeaderName, customHeaderValue.toString());
        }

    }
    return len;
}

From source file:org.apache.axis2.jaxws.message.impl.MessageImpl.java

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

    // TODO: /*w  ww.  j a  v a 2  s.co  m*/
    // This is a non performant way to create SOAPMessage. I will serialize
    // the xmlpart content and then create an InputStream of byte.
    // Finally create SOAPMessage using this InputStream.
    // The real solution may involve using non-spec, implementation
    // constructors to create a Message from an Envelope
    try {
        if (log.isDebugEnabled()) {
            log.debug("start getAsSOAPMessage");
        }
        // Get OMElement from XMLPart.
        OMElement element = xmlPart.getAsOMElement();

        // Get the namespace so that we can determine SOAP11 or SOAP12
        OMNamespace ns = element.getNamespace();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        element.serialize(outStream);

        // In some cases (usually inbound) the builder will not be closed after
        // serialization.  In that case it should be closed manually.
        if (element.getBuilder() != null && !element.getBuilder().isCompleted()) {
            element.close(false);
        }

        byte[] bytes = outStream.toByteArray();

        if (log.isDebugEnabled()) {
            String text = new String(bytes);
            log.debug("  inputstream = " + text);
        }

        // Create InputStream
        ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);

        // Create MessageFactory that supports the version of SOAP in the om element
        MessageFactory mf = getSAAJConverter().createMessageFactory(ns.getNamespaceURI());

        // Create soapMessage object from Message Factory using the input
        // stream created from OM.

        // Get the MimeHeaders from the transportHeaders map
        MimeHeaders defaultHeaders = new MimeHeaders();
        if (transportHeaders != null) {
            Iterator it = transportHeaders.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                if (entry.getValue() == null) {
                    // This is not necessarily a problem; log it and make sure not to NPE
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "  Not added to transport header. header =" + key + " because value is null;");
                    }
                } else if (entry.getValue() instanceof String) {
                    // Normally there is one value per key
                    if (log.isDebugEnabled()) {
                        log.debug("  add transport header. header =" + key + " value = " + entry.getValue());
                    }
                    defaultHeaders.addHeader(key, (String) entry.getValue());
                } else {
                    // There may be multiple values for each key.  This code
                    // assumes the value is an array of String.
                    String values[] = (String[]) entry.getValue();
                    for (int i = 0; i < values.length; i++) {
                        if (log.isDebugEnabled()) {
                            log.debug("  add transport header. header =" + key + " value = " + values[i]);
                        }
                        defaultHeaders.addHeader(key, values[i]);
                    }
                }
            }
        }

        // Toggle based on SOAP 1.1 or SOAP 1.2
        String contentType = null;
        if (ns.getNamespaceURI().equals(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE)) {
            contentType = SOAPConstants.SOAP_1_1_CONTENT_TYPE;
        } else {
            contentType = SOAPConstants.SOAP_1_2_CONTENT_TYPE;
        }

        // Override the content-type
        String ctValue = contentType + "; charset=UTF-8";
        defaultHeaders.setHeader("Content-type", ctValue);
        if (log.isDebugEnabled()) {
            log.debug("  setContentType =" + ctValue);
        }
        SOAPMessage soapMessage = mf.createMessage(defaultHeaders, inStream);

        // At this point the XMLPart is still an OMElement.  
        // We need to change it to the new SOAPEnvelope.
        createXMLPart(soapMessage.getSOAPPart().getEnvelope());

        // If axiom read the message from the input stream, 
        // then one of the attachments is a SOAPPart.  Ignore this attachment
        String soapPartContentID = getSOAPPartContentID(); // This may be null

        if (log.isDebugEnabled()) {
            log.debug("  soapPartContentID =" + soapPartContentID);
        }

        List<String> dontCopy = new ArrayList<String>();
        if (soapPartContentID != null) {
            dontCopy.add(soapPartContentID);
        }

        // Add any new attachments from the SOAPMessage to this Message
        Iterator it = soapMessage.getAttachments();
        while (it.hasNext()) {

            AttachmentPart ap = (AttachmentPart) it.next();
            String cid = ap.getContentId();
            if (log.isDebugEnabled()) {
                log.debug("  add SOAPMessage attachment to Message.  cid = " + cid);
            }
            addDataHandler(ap.getDataHandler(), cid);
            dontCopy.add(cid);
        }

        // Add the attachments from this Message to the SOAPMessage
        for (String cid : getAttachmentIDs()) {
            DataHandler dh = attachments.getDataHandler(cid);
            if (!dontCopy.contains(cid)) {
                if (log.isDebugEnabled()) {
                    log.debug("  add Message attachment to SoapMessage.  cid = " + cid);
                }
                AttachmentPart ap = MessageUtils.createAttachmentPart(cid, dh, soapMessage);
                soapMessage.addAttachmentPart(ap);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("  The SOAPMessage has the following attachments");
            Iterator it2 = soapMessage.getAttachments();
            while (it2.hasNext()) {
                AttachmentPart ap = (AttachmentPart) it2.next();
                log.debug("    AttachmentPart cid=" + ap.getContentId());
                log.debug("        contentType =" + ap.getContentType());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("end getAsSOAPMessage");
        }
        return soapMessage;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }

}

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

@Validated
@Test// w w  w  .j  a  va 2s .com
public void testMultipleAttachments() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();

    AttachmentPart a1 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a1.setContentType("text/xml");
    msg.addAttachmentPart(a1);
    AttachmentPart a2 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a2.setContentType("text/xml");
    msg.addAttachmentPart(a2);
    AttachmentPart a3 = msg.createAttachmentPart(new DataHandler("text", "text/plain"));
    a3.setContentType("text/plain");
    msg.addAttachmentPart(a3);

    assertTrue(msg.countAttachments() == 3);

    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");

    int nAttachments = 0;
    Iterator iterator = msg.getAttachments(mimeHeaders);
    while (iterator.hasNext()) {
        nAttachments++;
        AttachmentPart ap = (AttachmentPart) iterator.next();
        assertTrue(ap.equals(a1) || ap.equals(a2));
    }
    assertTrue(nAttachments == 2);
}