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:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*www . ja  v a2s  . co  m*/
public void testGetAttachmentsFiltered() throws Exception {
    SOAPMessage message = getFactory().createMessage();

    AttachmentPart att1 = message.createAttachmentPart();
    att1.addMimeHeader("Content-Type", "text/plain");
    message.addAttachmentPart(att1);

    AttachmentPart att2 = message.createAttachmentPart();
    att2.addMimeHeader("Content-Type", "application/octet-stream");
    message.addAttachmentPart(att2);

    AttachmentPart att3 = message.createAttachmentPart();
    att3.addMimeHeader("Content-ID", "<123456@example.com>");
    att3.addMimeHeader("Content-Type", "text/plain");
    message.addAttachmentPart(att3);

    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", "text/plain");
    Iterator it = message.getAttachments(headers);
    assertTrue(it.hasNext());
    assertSame(att1, it.next());
    assertTrue(it.hasNext());
    assertSame(att3, it.next());
    assertFalse(it.hasNext());
}

From source file:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java

private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException {
    log.debug("Entered send: " + cb.getName());

    // set up the factories and create a SOAP factory
    SOAPConnection soapConnection;
    Document doc = null;/*from w ww. j  a  v a 2s .c o m*/
    URL endpoint = null;
    try {
        soapConnection = SOAPConnectionFactory.newInstance().createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create a message from the message factory.
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Set the SOAP Action here
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", cb.getAction());

        // set credentials
        //         String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes());
        String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64(
                (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()));
        headers.addHeader("Authorization", "Basic " + authorization);
        log.debug("Authentication: " + authorization);

        // create a SOAP part have populate the envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);

        SOAPHeader head = envelope.getHeader();
        if (head == null)
            head = envelope.addHeader();

        // create a SOAP body
        SOAPBody body = envelope.getBody();

        log.debug("Request XSL Style Sheet:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl())));

        // convert request string to document and then transform
        body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl()));

        // build the request structure
        soapMessage.saveChanges();
        log.debug("Soap request successfully built: ");
        log.debug("  Body:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body))));

        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", shConfig.getProxyHost());
            System.setProperty("http.proxyPort", "" + shConfig.getProxyPort());
            if (shConfig.useProxyCredentials()) {
                System.setProperty("http.proxyUser", shConfig.getProxyUser());
                System.setProperty("http.proxyPassword", shConfig.getProxyPassword());
            }
        }

        endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint()));

        // now make that call over the SOAP connection
        SOAPMessage reply = null;
        AdapterException ae = null;

        for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) {
            log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint);
            try {
                reply = soapConnection.call(soapMessage, endpoint);
                log.debug("Attempt " + i + ": received response: " + reply);
            } catch (Exception e) {
                ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint),
                        e);
                Thread.sleep(100);
            }
        }

        // close down the connection
        soapConnection.close();

        if (reply == null)
            throw ae;

        SOAPFault fault = reply.getSOAPBody().getFault();
        if (fault == null) {
            doc = reply.getSOAPBody().extractContentAsDocument();
        } else {
            // Extracts the entire Soap Fault message coming back from CIS
            String faultString = XmlUtils.nodeToString(fault);
            throw new AdapterException(503, faultString, null);
        }
    } catch (AdapterException e) {
        throw e;
    } catch (Exception e) {
        throw new AdapterException(504,
                String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())),
                e);
    } finally {
        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "false");
        }
    }
    log.debug("Exiting send: " + cb.getName());

    return doc;
}

From source file:hk.hku.cecid.corvus.ws.EBMSMessageHistoryQuerySenderTest.java

private EBMSMessageHistoryRequestData getHttpRequestData() throws Exception {
    // Check content Type
    String contentType = monitor.getContentType();

    if (contentType == null) {
        System.out.println((monitor == null ? "Null Monitor" : "Monitor not null"));
        System.out.println("Lengeth " + monitor.getContentLength());
        Assert.fail("Null Content");
    }// w  ww  .  ja  v a2  s .  co m

    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "text/xml", mediaType);

    // Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.    
    RequestContext rc = new RequestContext() {
        public String getCharacterEncoding() {
            return "charset=utf-8";
        }

        public int getContentLength() {
            return monitor.getContentLength();
        }

        public String getContentType() {
            return monitor.getContentType();
        }

        public InputStream getInputStream() {
            return monitor.getInputStream();
        }
    };

    BufferedReader bReader = new BufferedReader(new InputStreamReader(monitor.getInputStream()));

    String strLine = "";
    do {
        strLine = bReader.readLine();
    } while (!strLine.contains("SOAP-ENV"));

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

    SOAPMessage msg = MessageFactory.newInstance().createMessage(header,
            new ByteArrayInputStream(strLine.getBytes()));

    EBMSMessageHistoryRequestData data = new EBMSMessageHistoryRequestData();
    data.setMessageId(getElementValue(msg.getSOAPBody(), "tns:messageId"));
    data.setMessageBox(getElementValue(msg.getSOAPBody(), "tns:messageBox"));
    data.setStatus(getElementValue(msg.getSOAPBody(), "tns:status"));
    data.setService(getElementValue(msg.getSOAPBody(), "tns:service"));
    data.setAction(getElementValue(msg.getSOAPBody(), "tns:action"));
    data.setConversationId(getElementValue(msg.getSOAPBody(), "tns:conversationId"));
    data.setCpaId(getElementValue(msg.getSOAPBody(), "tns:cpaId"));
    return data;
}

From source file:com.wandrell.example.swss.test.util.test.integration.endpoint.AbstractITEndpoint.java

/**
 * Calls the web service being tested and returns the response.
 *
 * @param request/*from ww  w .  ja  v a 2 s  . co m*/
 *            request to the web service
 * @return the web service response
 * @throws SOAPException
 *             never, this is a required declaration
 */
protected final SOAPMessage callWebService(final SOAPMessage request) throws SOAPException {
    final SOAPConnectionFactory soapConnectionFactory; // Connection factory
    final MimeHeaders headers; // Message headers

    soapConnectionFactory = SOAPConnectionFactory.newInstance();

    // Sets the SOAP action
    headers = request.getMimeHeaders();
    headers.addHeader("SOAPAction", soapAction);
    request.saveChanges();

    return soapConnectionFactory.createConnection().call(request, wsURL);
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Extracts the SOAP response from an HttpResponse.
 *///from  w w  w .  j  a  v a  2 s  .  c  o  m
protected Message extractResponse(MessageContext msgContext, HttpResponse response) throws IOException {
    int returnCode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    if (entity != null && returnCode > 199 && returnCode < 300) {
        // SOAP return is OK - so fall through
    } else if (entity != null && 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 (entity != null && returnCode > 499 && returnCode < 600
            && Objects.equals(getMimeType(entity), "text/xml")) {
        // SOAP Fault should be in here - so fall through
    } else {
        String statusMessage = response.getStatusLine().getReasonPhrase();
        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);
        fault.setFaultDetailString("Return code: " + String.valueOf(returnCode)
                + (entity == null ? "" : "\n" + EntityUtils.toString(entity)));
        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, String.valueOf(returnCode));
        throw fault;
    }

    Header contentLocation = response.getFirstHeader(HttpHeaders.CONTENT_LOCATION);
    Message outMsg = new Message(entity.getContent(), false, Objects.toString(ContentType.get(entity), null),
            (contentLocation == null) ? null : contentLocation.getValue());
    // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
    MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
    for (Header responseHeader : response.getAllHeaders()) {
        responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
    }
    outMsg.setMessageType(Message.RESPONSE);
    return outMsg;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.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//from  ww w. ja va  2 s . c om
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        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);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    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 = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java

/**
 * Constructs and executes a SOAP message.  For {@code basic} authentication, YADA uses the 
 * java soap api, and the {@link SOAPConnection} object stored in the query object.  For 
 * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC}
 * in {@link #YADA_BIN}. /* w w  w .  ja  v  a2  s  . c  o m*/
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    String result = "";
    resetCountParameter(yq);
    SOAPConnection connection = (SOAPConnection) yq.getConnection();
    for (int row = 0; row < yq.getData().size(); row++) {
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();
        String soapUrl = yq.getSoap(row);

        try {
            this.endpoint = new URL(soapUrl);
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes());

            // Assume a SOAP message was built previously
            MimeHeaders mimeHeaders = message.getMimeHeaders();
            if ("basic".equals(this.soapAuth.toLowerCase())) {
                mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken));
                mimeHeaders.addHeader("SOAPAction", this.soapAction);
                mimeHeaders.addHeader("Content-Type", "text/xml");
                SOAPHeader header = message.getSOAPHeader();
                SOAPBody body = message.getSOAPBody();
                header.detachNode();

                l.debug("query:\n" + this.queryString);

                try {
                    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new ByteArrayInputStream(this.soapData.getBytes()));

                    //SOAPBodyElement docElement = 
                    body.addDocument(xml);

                    Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass));

                    SOAPMessage response = connection.call(message, this.endpoint);
                    try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) {
                        response.writeTo(responseOutputStream);
                        result = responseOutputStream.toString();
                    }
                } catch (IOException e) {
                    String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
                l.debug("SOAP Body:\n" + result);
            } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase())
                    || "negotiate".equals(this.soapAuth.toLowerCase())) {
                ArrayList<String> args = new ArrayList<>();
                args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC);
                args.add("-X");
                args.add("-s");
                args.add(this.soapSource + this.soapPath);
                args.add("-u");
                args.add(this.soapDomain + "\\" + this.soapUser);
                args.add("-p");
                args.add(this.soapPass);
                args.add("-a");
                args.add(this.soapAuth);
                args.add("-q");
                args.add(this.soapData);
                args.add("-t");
                args.add(this.soapAction);
                String[] cmds = args.toArray(new String[0]);
                l.debug("Executing soap request via script: " + Arrays.toString(cmds));
                String s = null;
                try {
                    ProcessBuilder pb = new ProcessBuilder(args);
                    l.debug(pb.environment().toString());
                    pb.redirectErrorStream(true);
                    Process p = pb.start();
                    try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        while ((s = si.readLine()) != null) {
                            l.debug(s);
                            if (null == result) {
                                result = "";
                            }
                            result += s;
                        }
                    }
                } catch (IOException e) {
                    String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'.  Make sure the curl executable is still accessible.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
            }
        } catch (SOAPException e) {
            String msg = "There was a problem creating or executing the SOAP message, or receiving the response.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (SAXException e) {
            String msg = "Unable to parse SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (ParserConfigurationException e) {
            String msg = "There was a problem creating the xml document for the SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (YADAResourceException e) {
            String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC;
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (MalformedURLException e) {
            String msg = "Can't create URL from provided source and path.";
            throw new YADAAdaptorExecutionException(msg, e);
        } finally {
            try {
                ConnectionFactory.releaseResources(connection, yq.getSoap().get(0));
            } catch (YADAConnectionException e) {
                l.error(e.getMessage());
            }
        }

        yqr.addResult(row, result);

    }

}

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

private MimeHeaders parseMimeHeaders(InputStream inputStream) throws IOException {
    MimeHeaders mimeHeaders = new MimeHeaders();
    if (inputStream instanceof TransportInputStream) {
        TransportInputStream transportInputStream = (TransportInputStream) inputStream;
        for (Iterator headerNames = transportInputStream.getHeaderNames(); headerNames.hasNext();) {
            String headerName = (String) headerNames.next();
            for (Iterator headerValues = transportInputStream.getHeaders(headerName); headerValues.hasNext();) {
                String headerValue = (String) headerValues.next();
                StringTokenizer tokenizer = new StringTokenizer(headerValue, ",");
                while (tokenizer.hasMoreTokens()) {
                    mimeHeaders.addHeader(headerName, tokenizer.nextToken().trim());
                }/*ww  w  .j a v  a  2 s. c om*/
            }
        }
    }
    return mimeHeaders;
}

From source file:fi.laverca.util.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 if there was an error sending the SOAP message
 *//* w w w.  ja va2 s .c  om*/
@Override
public void invoke(final MessageContext msgContext) throws AxisFault {

    HttpPost post = null;
    HttpResponse response = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }
    try {

        HttpClient httpClient = settings.get();

        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        Message reqMessage = msgContext.getRequestMessage();
        post = new HttpPost(targetURL.toString());

        // set false as default, addContentInfo can overwrite
        HttpParams params = post.getParams();
        HttpProtocolParams.setUseExpectContinue(params, false);

        addContextInfo(post, httpClient, msgContext, targetURL);

        MessageRequestEntity requestEntity = null;
        if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
            requestEntity = new GzipMessageRequestEntity(post, reqMessage, httpChunkStream);
        } else {
            requestEntity = new MessageRequestEntity(post, reqMessage, httpChunkStream);
        }
        post.setEntity(requestEntity);

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                params.setParameter(httpVersion, HttpVersion.HTTP_1_0);
            }
        }

        HttpContext localContext = new BasicHttpContext();

        if (httpClient == null) {
            // We might end up here if initThreadLocals() was not properly called
            log.fatal("Initialization failed: No HTTPClient");
            throw new AxisFault("Initialization failed: No HTTPClient");
        }

        response = httpClient.execute(post, localContext);
        int returnCode = response.getStatusLine().getStatusCode();

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

            try {
                String body = getResponseBodyAsString(response);
                fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, body));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                HttpClientUtils.closeQuietly(response);
                post.releaseConnection();
            }
        }

        // After this phase, the response and post are NOT to be closed/released
        // in this code path! See comments further below at "AXIS closure processing rules"

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

        Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                try {
                    releaseConnectionOnCloseStream.close();
                } catch (Throwable t) {
                    // ignore
                }
                throw new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
            }
        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = post.getAllHeaders();
        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());
        }

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

    } finally {

        // AXIS closure processing rules..
        //
        // 1: Always release the connection back to the pool
        //    IF it was ONE WAY invocation

        if (msgContext.isPropertyTrue("axis.one.way")) {
            HttpClientUtils.closeQuietly(response);
            if (post != null) {
                post.releaseConnection();
            }
        } else {
            log.debug("A HTTP POST which did NOT plan to release the HTTP connection back to the pool");
        }

        // 2: Otherwise the Axis machinery will process call
        //    close() on the releaseConnectionOnCloseStream.
    }

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

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 *     Create a SOAPMessage containing a registry request (e.g. SubmitObjectsRequest)
 *     @param req the InputStream to the registry request
 *     @return the created SOAPMessage//  w  ww.j a v  a2s.c  o  m
 */
public SOAPMessage createSOAPMessageFromRequestStream(InputStream reqStream)
        throws javax.xml.soap.SOAPException, IOException, javax.mail.internet.ParseException {
    InputStream is = createSOAPStreamFromRequestStream(reqStream);

    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, is);

    msg.saveChanges();

    return msg;
}