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:it.cnr.icar.eric.server.common.Utility.java

/**
 *     Create a SOAPMessage object from a InputStream to a SOAPMessage
 *     @param soapStream the InputStream to the SOAPMessage
 *     @return the created SOAPMessage//from   w w  w. java2s.  c  om
 */
public SOAPMessage createSOAPMessageFromSOAPStream(InputStream soapStream)
        throws javax.xml.soap.SOAPException, IOException, javax.mail.internet.ParseException {

    javax.xml.soap.MimeHeaders mimeHeaders = new javax.xml.soap.MimeHeaders();

    javax.mail.internet.ContentType contentType = new javax.mail.internet.ContentType("text/xml"); //"multipart/related");

    String contentTypeStr = contentType.toString();

    //System.err.println("contentTypeStr = '" + contentTypeStr + "'");
    mimeHeaders.addHeader("Content-Type", contentTypeStr);
    mimeHeaders.addHeader("Content-Id", "ebXML Registry SOAP request");

    javax.xml.soap.MessageFactory factory = javax.xml.soap.MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage(mimeHeaders, soapStream);

    // this saveChanges() call breaks SaaJ attachment branch with JDK6 code switch!!!
    // resulting in broken multipart/related + length calculated wrong 
    //        msg.saveChanges();

    return msg;
}

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

/**
 * Reads the SOAP response back from the server
 *
 * @param msgContext message context/*  w w  w. j  ava  2 s .c o 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:com.maxl.java.aips2sqlite.AllDown.java

public void downRefdataPharmaXml(String file_refdata_pharma_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {//from  w ww .j ava  2 s  .  c o m
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Refdatabase pharma file... ");
        else {
            pb.init("- Downloading Refdatabase pharma file... ");
            pb.start();
        }

        // Create soaprequest
        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();
        // Set SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://refdatabase.refdata.ch/Pharma/Download");
        // Set SOAP main request part
        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("DownloadArticleInput");
        soapBodyElement1.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/");
        SOAPElement soapBodyElement2 = soapBodyElement1.addChildElement("ATYPE");
        soapBodyElement2.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/Article_in");
        soapBodyElement2.addTextNode("ALL");
        soapRequest.saveChanges();
        // If needed print out soapRequest in a pretty format
        // System.out.println(prettyFormatSoapXml(soapRequest));
        // Create connection to SOAP server
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        // wsURL contains service end point
        String wsURL = "http://refdatabase.refdata.ch/Service/Article.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);
        // Extract response
        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless!          
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");

        long len = writeToFile(xmlBody, file_refdata_pharma_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Refdata pharma file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downRefdataPharmaXml'");
        e.printStackTrace();
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downRefdataPartnerXml(String file_refdata_partner_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {/*  w ww.  j a va2s  . c o m*/
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Refdata partner file... ");
        else {
            pb.init("- Downloading Refdata partner file... ");
            pb.start();
        }

        // Create soaprequest
        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();
        // Set SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://refdatabase.refdata.ch/Download");
        // Set SOAP main request part
        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("DownloadPartnerInput");
        soapBodyElement1.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/");
        SOAPElement soapBodyElement2 = soapBodyElement1.addChildElement("PTYPE");
        soapBodyElement2.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/Partner_in");
        soapBodyElement2.addTextNode("ALL");
        soapRequest.saveChanges();
        // If needed print out soapRequest in a pretty format
        // System.out.println(prettyFormatSoapXml(soapRequest));
        // Create connection to SOAP server
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        // wsURL contains service end point
        String wsURL = "http://refdatabase.refdata.ch/Service/Partner.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);
        // Extract response
        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless!          
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");

        long len = writeToFile(xmlBody, file_refdata_partner_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Refdata partner file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downRefdataPartnerXml'");
        e.printStackTrace();
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downSwissindexXml(String language, String file_refdata_pharma_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {/*from   w  ww.j av a2s  .c  om*/
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Swissindex (" + language + ") file... ");
        else {
            pb.init("- Downloading Swissindex (" + language + ") file... ");
            pb.start();
        }

        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

        // Setting SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://swissindex.e-mediat.net/SwissindexPharma_out_V101/DownloadAll");

        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("pharmacode");
        soapBodyElement1.addNamespaceDeclaration("",
                "http://swissindex.e-mediat.net/SwissindexPharma_out_V101");
        soapBodyElement1.addTextNode("DownloadAll");
        SOAPElement soapBodyElement2 = soapBody.addChildElement("lang");
        soapBodyElement2.addNamespaceDeclaration("",
                "http://swissindex.e-mediat.net/SwissindexPharma_out_V101");
        if (language.equals("DE"))
            soapBodyElement2.addTextNode("DE");
        else if (language.equals("FR"))
            soapBodyElement2.addTextNode("FR");
        else {
            System.err.println("down_swissindex_xml: wrong language!");
            return;
        }
        soapRequest.saveChanges();

        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        String wsURL = "https://swissindex.refdata.ch/Swissindex/Pharma/ws_Pharma_V101.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);

        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless! 
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");
        long len = writeToFile(xmlBody, file_refdata_pharma_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Swissindex (" + language + ") file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downSwissindexXml'");
        e.printStackTrace();
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.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/*  w w w .  j  av  a  2  s  .  c  o m*/
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }

    // Catch all exceptions and turn them into AxisFaults
    try {
        // Get the URL
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // Get the HttpClient
        HttpClient httpClient = (HttpClient) msgContext.getProperty(
                org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.HTTPCLIENT_PROPERTY);

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

        boolean http10 = false;
        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                http10 = true;
            }
            // assume 1.1
        }

        HttpRequestBase method;

        if (posting) {
            HttpPost postMethod = new HttpPost(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            HttpProtocolParams.setUseExpectContinue(postMethod.getParams(), false);

            Message reqMessage = msgContext.getRequestMessage();

            boolean httpChunkStream = addContextInfo(postMethod, msgContext);

            HttpEntity requestEntity = null;
            requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream, http10 || !httpChunkStream);
            postMethod.setEntity(requestEntity);
            method = postMethod;
        } else {
            method = new HttpGet(targetURL.toString());
        }

        if (http10)
            HttpProtocolParams.setVersion(method.getParams(), new ProtocolVersion("HTTP", 1, 0));

        BackgroundHTTPThread methodThread = new BackgroundHTTPThread(httpClient, method);
        methodThread.start();
        try {
            int returnCode = methodThread.getResponseCode();

            String contentType = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_TYPE);
            String contentLocation = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LOCATION);
            String contentLength = getHeader(methodThread, 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 = methodThread.getResponseStatus();
                AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

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

            String contentEncoding = methodThread.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
            if (contentEncoding != null) {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding + "' found", null, null);
                throw fault;
            }

            Map<String, List<String>> responseHeaders = methodThread.getResponseHeaders();

            InputStream dataStream = methodThread.getSafeInputStream();

            Message outMsg = new Message(new BackgroundInputStream(methodThread, dataStream), false,
                    contentType, contentLocation);

            // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
            MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
            for (String name : responseHeaders.keySet()) {
                List<String> values = responseHeaders.get(name);
                for (String value : values) {
                    responseMimeHeaders.addHeader(name, value);
                }
            }
            outMsg.setMessageType(Message.RESPONSE);

            // Put the message in the message context.
            msgContext.setResponseMessage(outMsg);

            // Pass off the method thread to the stream for closure
            methodThread = null;
        } finally {
            if (methodThread != null) {
                methodThread.abort();
                methodThread.finishUp();
            }
        }

    } catch (AxisFault af) {
        log.debug(af);
        throw af;
    } 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.manifoldcf.sharepoint.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  om*/
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }

    // Catch all exceptions and turn them into AxisFaults
    try {
        // Get the URL
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // Get the HttpClient
        HttpClient httpClient = (HttpClient) msgContext.getProperty(HTTPCLIENT_PROPERTY);

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

        boolean http10 = false;
        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                http10 = true;
            }
            // assume 1.1
        }

        HttpRequestBase method;

        if (posting) {
            HttpPost postMethod = new HttpPost(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            HttpProtocolParams.setUseExpectContinue(postMethod.getParams(), false);

            Message reqMessage = msgContext.getRequestMessage();

            boolean httpChunkStream = addContextInfo(postMethod, msgContext);

            HttpEntity requestEntity = null;
            requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream, http10 || !httpChunkStream);
            postMethod.setEntity(requestEntity);
            method = postMethod;
        } else {
            method = new HttpGet(targetURL.toString());
        }

        if (http10)
            HttpProtocolParams.setVersion(method.getParams(), new ProtocolVersion("HTTP", 1, 0));

        BackgroundHTTPThread methodThread = new BackgroundHTTPThread(httpClient, method);
        methodThread.start();
        try {
            int returnCode = methodThread.getResponseCode();

            String contentType = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_TYPE);
            String contentLocation = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LOCATION);
            String contentLength = getHeader(methodThread, 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 = methodThread.getResponseStatus();
                AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

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

            String contentEncoding = methodThread.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
            if (contentEncoding != null) {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding + "' found", null, null);
                throw fault;
            }

            Map<String, List<String>> responseHeaders = methodThread.getResponseHeaders();

            InputStream dataStream = methodThread.getSafeInputStream();

            Message outMsg = new Message(new BackgroundInputStream(methodThread, dataStream), false,
                    contentType, contentLocation);

            // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
            MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
            for (String name : responseHeaders.keySet()) {
                List<String> values = responseHeaders.get(name);
                for (String value : values) {
                    responseMimeHeaders.addHeader(name, value);
                }
            }
            outMsg.setMessageType(Message.RESPONSE);

            // Put the message in the message context.
            msgContext.setResponseMessage(outMsg);

            // Pass off the method thread to the stream for closure
            methodThread = null;
        } finally {
            if (methodThread != null) {
                methodThread.abort();
                methodThread.finishUp();
            }
        }

    } catch (AxisFault af) {
        log.debug(af);
        throw af;
    } 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.manifoldcf.connectorcommon.common.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  va  2 s . c om*/
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }

    // Catch all exceptions and turn them into AxisFaults
    try {
        // Get the URL
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // Get the HttpClient
        HttpClient httpClient = (HttpClient) msgContext.getProperty(HTTPCLIENT_PROPERTY);

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

        boolean http10 = false;
        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                http10 = true;
            }
            // assume 1.1
        }

        HttpRequestBase method;

        if (posting) {
            HttpPost postMethod = new HttpPost(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            //HttpProtocolParams.setUseExpectContinue(postMethod.getParams(),false);

            Message reqMessage = msgContext.getRequestMessage();

            boolean httpChunkStream = addContextInfo(postMethod, msgContext);

            HttpEntity requestEntity = null;
            requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream, http10 || !httpChunkStream);
            postMethod.setEntity(requestEntity);
            method = postMethod;
        } else {
            method = new HttpGet(targetURL.toString());
        }

        //if (http10)
        //  HttpProtocolParams.setVersion(method.getParams(),new ProtocolVersion("HTTP",1,0));

        BackgroundHTTPThread methodThread = new BackgroundHTTPThread(httpClient, method);
        methodThread.start();
        try {
            int returnCode = methodThread.getResponseCode();

            String contentType = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_TYPE);
            String contentLocation = getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LOCATION);
            String contentLength = getHeader(methodThread, 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 = methodThread.getResponseStatus();
                AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

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

            String contentEncoding = methodThread.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
            if (contentEncoding != null) {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding + "' found", null, null);
                throw fault;
            }

            Map<String, List<String>> responseHeaders = methodThread.getResponseHeaders();

            InputStream dataStream = methodThread.getSafeInputStream();

            Message outMsg = new Message(new BackgroundInputStream(methodThread, dataStream), false,
                    contentType, contentLocation);

            // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
            MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
            for (String name : responseHeaders.keySet()) {
                List<String> values = responseHeaders.get(name);
                for (String value : values) {
                    responseMimeHeaders.addHeader(name, value);
                }
            }
            outMsg.setMessageType(Message.RESPONSE);

            // Put the message in the message context.
            msgContext.setResponseMessage(outMsg);

            // Pass off the method thread to the stream for closure
            methodThread = null;
        } finally {
            if (methodThread != null) {
                methodThread.abort();
                methodThread.finishUp();
            }
        }

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

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

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 * /* ww  w .  j  a  va 2  s. c  o m*/
 * @param msgContext
 *            the messsage context
 * 
 * @throws AxisFault
 */
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());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler());

        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:com.jaspersoft.ireport.jasperserver.ws.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  ww  . ja v  a  2 s.co  m*/
 */
public void invoke(MessageContext msgContext) throws AxisFault {

    //test();

    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.

        //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);

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

            method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength());
            ((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 = targetURL.getHost();
            String path = targetURL.getPath();
            boolean secure = targetURL.getProtocol().equals("https");

            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(method);

        org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);

        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"));
    }
}