Example usage for javax.xml.soap SOAPMessage getSOAPPart

List of usage examples for javax.xml.soap SOAPMessage getSOAPPart

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage getSOAPPart.

Prototype

public abstract SOAPPart getSOAPPart();

Source Link

Document

Gets the SOAP part of this SOAPMessage object.

Usage

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

private SOAPMessage createFaultSOAPMessage(java.lang.Throwable e, SOAPHeader sh) {
    SOAPMessage msg = null;
    if (log.isDebugEnabled()) {
        log.debug("Creating Fault SOAP Message with Throwable:", e);
    }/*from  w ww.  ja v a 2s . c  o m*/
    try {
        // Will this method be "legacy" ebRS 3.0 spec-compliant and
        // return a URN as the <faultcode/> value? Default expectation
        // is of a an older client. Overridden to instead be SOAP
        // 1.1-compliant and return a QName as the faultcode value when
        // we know (for sure) client supports new approach.
        boolean legacyFaultCode = true;

        // get SOAPHeaderElement list from the received message
        // TODO: if additional capabilities are needed, move code to
        // elsewhere
        if (null != sh) {
            Iterator<?> headers = sh.examineAllHeaderElements();
            while (headers.hasNext()) {
                Object obj = headers.next();

                // confirm expected Iterator content
                if (obj instanceof SOAPHeaderElement) {
                    SOAPHeaderElement header = (SOAPHeaderElement) obj;
                    Name headerName = header.getElementName();

                    // check this SOAP header for relevant capability
                    // signature
                    if (headerName.getLocalName().equals(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName)
                            && headerName.getURI().equals(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace)
                            && header.getValue().equals(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes)) {
                        legacyFaultCode = false;
                        // only interested in one client capability
                        break;
                    }
                }
            }
        }

        msg = MessageFactory.newInstance().createMessage();
        SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
        SOAPFault fault = msg.getSOAPBody().addFault();

        // set faultCode
        String exceptionName = e.getClass().getName();
        // TODO: SAAJ 1.3 has introduced preferred QName interfaces
        Name name = env.createName(exceptionName, "ns1", BindingUtility.SOAP_FAULT_PREFIX);
        fault.setFaultCode(name);
        if (legacyFaultCode) {
            // we now have an element child, munge its text (hack alert)
            Node faultCode = fault.getElementsByTagName("faultcode").item(0);
            // Using Utility.setTextContent() implementation since Java
            // WSDP 1.5 (containing an earlier DOM API) does not
            // support Node.setTextContent().
            Utility.setTextContent(faultCode, BindingUtility.SOAP_FAULT_PREFIX + ":" + exceptionName);
        }

        // set faultString
        String errorMsg = e.getMessage();
        if (errorMsg == null) {
            errorMsg = "NULL";
        }
        fault.setFaultString(errorMsg);

        // create faultDetail with one entry
        Detail det = fault.addDetail();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String str = sw.toString();

        name = env.createName("StackTrace", "rs", "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0");
        DetailEntry de = det.addDetailEntry(name);
        de.setValue(str);
        // de.addTextNode(str);

        // TODO: Need to put baseURL for this registry here

        msg.saveChanges();
    } catch (SOAPException ex) {
        log.warn(ex, ex);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

/**
 * This method is a copy of the respective method from RegistrySOAPServlet.
 * The SAML-based Servlet returns X.509 certificate base SOAP messages.
 * //from  ww w  .j a  va  2 s  . c  om
 */

private SOAPMessage createFaultSOAPMessage(java.lang.Throwable e, SOAPHeader sh) {
    SOAPMessage msg = null;

    if (log.isDebugEnabled()) {
        log.debug("Creating Fault SOAP Message with Throwable:", e);
    }

    try {
        // Will this method be "legacy" ebRS 3.0 spec-compliant and
        // return a URN as the <faultcode/> value? Default expectation
        // is of a an older client. Overridden to instead be SOAP
        // 1.1-compliant and return a QName as the faultcode value when
        // we know (for sure) client supports new approach.
        boolean legacyFaultCode = true;

        // get SOAPHeaderElement list from the received message
        // TODO: if additional capabilities are needed, move code to
        // elsewhere
        if (null != sh) {
            Iterator<?> headers = sh.examineAllHeaderElements();
            while (headers.hasNext()) {
                Object obj = headers.next();

                // confirm expected Iterator content
                if (obj instanceof SOAPHeaderElement) {
                    SOAPHeaderElement header = (SOAPHeaderElement) obj;
                    Name headerName = header.getElementName();

                    // check this SOAP header for relevant capability
                    // signature
                    if (headerName.getLocalName().equals(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName)
                            && headerName.getURI().equals(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace)
                            && header.getValue().equals(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes)) {
                        legacyFaultCode = false;
                        // only interested in one client capability
                        break;
                    }
                }
            }
        }

        msg = MessageFactory.newInstance().createMessage();
        SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
        SOAPFault fault = msg.getSOAPBody().addFault();

        // set faultCode
        String exceptionName = e.getClass().getName();

        // TODO: SAAJ 1.3 has introduced preferred QName interfaces
        Name name = env.createName(exceptionName, "ns1", BindingUtility.SOAP_FAULT_PREFIX);
        fault.setFaultCode(name);
        if (legacyFaultCode) {
            // we now have an element child, munge its text (hack alert)
            Node faultCode = fault.getElementsByTagName("faultcode").item(0);

            // Using Utility.setTextContent() implementation since Java
            // WSDP 1.5 (containing an earlier DOM API) does not
            // support Node.setTextContent().
            Utility.setTextContent(faultCode, BindingUtility.SOAP_FAULT_PREFIX + ":" + exceptionName);
        }

        // set faultString
        String errorMsg = e.getMessage();
        if (errorMsg == null) {
            errorMsg = "NULL";
        }
        fault.setFaultString(errorMsg);

        // create faultDetail with one entry
        Detail det = fault.addDetail();

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String str = sw.toString();

        name = env.createName("StackTrace", "rs", "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0");

        DetailEntry de = det.addDetailEntry(name);
        de.setValue(str);
        // de.addTextNode(str);

        // TODO: Need to put baseURL for this registry here

        msg.saveChanges();

    } catch (SOAPException ex) {
        log.warn(ex, ex);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

private SOAPMessage createResponseSOAPMessage(Object obj) {
    SOAPMessage msg = null;

    try {/*from ww w .j  av  a 2 s. com*/
        RegistryResponseType ebRegistryResponseType = null;

        if (obj instanceof it.cnr.icar.eric.server.interfaces.Response) {
            Response r = (Response) obj;
            ebRegistryResponseType = r.getMessage();

        } else if (obj instanceof java.lang.Throwable) {
            Throwable t = (Throwable) obj;
            ebRegistryResponseType = it.cnr.icar.eric.server.common.Utility.getInstance()
                    .createRegistryResponseFromThrowable(t, "RegistrySOAPServlet", "Unknown");
        }

        //Now add resp to SOAPMessage
        StringWriter sw = new StringWriter();
        //            javax.xml.bind.Marshaller marshaller = bu.rsFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (ebRegistryResponseType.getClass() == RegistryResponseType.class) {
            // if ComplexType is explicit, wrap it into Element
            // only RegistryResponeType is explicit -> equal test instead of isinstance
            JAXBElement<RegistryResponseType> ebRegistryResponse = bu.rsFac
                    .createRegistryResponse(ebRegistryResponseType);
            marshaller.marshal(ebRegistryResponse, sw);

        } else {
            // if ComplexType is anonymous, it can be marshalled directly 
            marshaller.marshal(ebRegistryResponseType, sw);
        }

        //Now get the RegistryResponse as a String
        String respStr = sw.toString();

        // Use Unicode (utf-8) to getBytes (server and client). Rely on platform default encoding is not safe.
        InputStream soapStream = it.cnr.icar.eric.server.common.Utility.getInstance()
                .createSOAPStreamFromRequestStream(new ByteArrayInputStream(respStr.getBytes("utf-8")));

        boolean signRequired = Boolean
                .valueOf(RegistryProperties.getInstance().getProperty("eric.interfaces.soap.signedResponse"))
                .booleanValue();

        msg = it.cnr.icar.eric.server.common.Utility.getInstance().createSOAPMessageFromSOAPStream(soapStream);

        if (signRequired) {

            AuthenticationServiceImpl auService = AuthenticationServiceImpl.getInstance();
            PrivateKey privateKey = auService.getPrivateKey(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR,
                    AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);
            java.security.cert.Certificate[] certs = auService
                    .getCertificateChain(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);

            CredentialInfo credentialInfo = new CredentialInfo(null, (X509Certificate) certs[0], certs,
                    privateKey);

            SOAPPart sp = msg.getSOAPPart();
            SOAPEnvelope se = sp.getEnvelope();

            WSS4JSecurityUtilBST.signSOAPEnvelopeOnServerBST(se, credentialInfo);

            //                msg = SoapSecurityUtil.getInstance().signSoapMessage(msg, credentialInfo);

        }

        // msg.writeTo(new FileOutputStream(new File("signedResponse.xml")));
        soapStream.close();
    } catch (IOException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (SOAPException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (javax.xml.bind.JAXBException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (ParseException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (RegistryException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

/**
 * This method is a copy of the respective method from RegistrySOAPServlet.
 * The SAML-based Servlet returns X.509 certificate base SOAP messages.
 * /*  w w  w. j a  v  a2  s  .  c o m*/
 */

private SOAPMessage createResponseSOAPMessage(Object obj) {

    SOAPMessage msg = null;

    try {
        RegistryResponseType ebRegistryResponseType = null;

        if (obj instanceof it.cnr.icar.eric.server.interfaces.Response) {
            Response r = (Response) obj;
            ebRegistryResponseType = r.getMessage();

        } else if (obj instanceof java.lang.Throwable) {
            Throwable t = (Throwable) obj;
            ebRegistryResponseType = it.cnr.icar.eric.server.common.Utility.getInstance()
                    .createRegistryResponseFromThrowable(t, "RegistrySOAPServlet", "Unknown");
        }

        // Now add resp to SOAPMessage
        StringWriter sw = new StringWriter();
        // javax.xml.bind.Marshaller marshaller =
        // bu.rsFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (ebRegistryResponseType.getClass() == RegistryResponseType.class) {
            // if ComplexType is explicit, wrap it into Element
            // only RegistryResponeType is explicit -> equal test instead of
            // isinstance
            JAXBElement<RegistryResponseType> ebRegistryResponse = bu.rsFac
                    .createRegistryResponse(ebRegistryResponseType);
            marshaller.marshal(ebRegistryResponse, sw);

        } else {
            // if ComplexType is anonymous, it can be marshalled directly
            marshaller.marshal(ebRegistryResponseType, sw);
        }

        // Now get the RegistryResponse as a String
        String respStr = sw.toString();

        // Use Unicode (utf-8) to getBytes (server and client). Rely on
        // platform default encoding is not safe.
        InputStream soapStream = it.cnr.icar.eric.server.common.Utility.getInstance()
                .createSOAPStreamFromRequestStream(new ByteArrayInputStream(respStr.getBytes("utf-8")));

        boolean signRequired = Boolean
                .valueOf(RegistryProperties.getInstance().getProperty("eric.interfaces.soap.signedResponse"))
                .booleanValue();

        msg = it.cnr.icar.eric.server.common.Utility.getInstance().createSOAPMessageFromSOAPStream(soapStream);

        if (signRequired) {

            AuthenticationServiceImpl auService = AuthenticationServiceImpl.getInstance();
            PrivateKey privateKey = auService.getPrivateKey(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR,
                    AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);
            java.security.cert.Certificate[] certs = auService
                    .getCertificateChain(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);

            CredentialInfo credentialInfo = new CredentialInfo(null, (X509Certificate) certs[0], certs,
                    privateKey, null);

            SOAPPart sp = msg.getSOAPPart();
            SOAPEnvelope se = sp.getEnvelope();

            WSS4JSecurityUtilSAML.signSOAPEnvelopeOnServerBST(se, credentialInfo);

        }

        // msg.writeTo(new FileOutputStream(new
        // File("signedResponse.xml")));
        soapStream.close();
    } catch (IOException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (SOAPException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (javax.xml.bind.JAXBException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (ParseException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (RegistryException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java

@Override
public SOAPMessage invoke(SOAPMessage request) {
    String result;//from  w ww  . ja v  a2  s  .  c  o  m
    PipeLineSessionBase pipelineSession = new PipeLineSessionBase();
    String correlationId = Misc.createSimpleUUID();
    log.debug(getLogPrefix(correlationId) + "received message");

    if (request == null) {
        String faultcode = "soap:Server";
        String faultstring = "SOAPMessage is null";
        String httpRequestMethod = (String) webServiceContext.getMessageContext()
                .get(MessageContext.HTTP_REQUEST_METHOD);
        if (!"POST".equals(httpRequestMethod)) {
            faultcode = "soap:Client";
            faultstring = "Request was send using '" + httpRequestMethod + "' instead of 'POST'";
        }
        result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body><soap:Fault>" + "<faultcode>" + faultcode + "</faultcode>" + "<faultstring>"
                + faultstring + "</faultstring>" + "</soap:Fault></soap:Body></soap:Envelope>";
    } else {
        // Make mime headers in request available as session key
        @SuppressWarnings("unchecked")
        Iterator<MimeHeader> mimeHeaders = request.getMimeHeaders().getAllHeaders();
        String mimeHeadersXml = getMimeHeadersXml(mimeHeaders).toXML();
        pipelineSession.put("mimeHeaders", mimeHeadersXml);

        // Make attachments in request (when present) available as session keys
        int i = 1;
        XmlBuilder attachments = new XmlBuilder("attachments");
        @SuppressWarnings("unchecked")
        Iterator<AttachmentPart> attachmentParts = request.getAttachments();
        while (attachmentParts.hasNext()) {
            try {
                InputStreamAttachmentPart attachmentPart = new InputStreamAttachmentPart(
                        attachmentParts.next());

                XmlBuilder attachment = new XmlBuilder("attachment");
                attachments.addSubElement(attachment);
                XmlBuilder sessionKey = new XmlBuilder("sessionKey");
                sessionKey.setValue("attachment" + i);
                attachment.addSubElement(sessionKey);
                pipelineSession.put("attachment" + i, attachmentPart.getInputStream());
                log.debug(getLogPrefix(correlationId) + "adding attachment [attachment" + i + "] to session");

                @SuppressWarnings("unchecked")
                Iterator<MimeHeader> attachmentMimeHeaders = attachmentPart.getAllMimeHeaders();
                attachment.addSubElement(getMimeHeadersXml(attachmentMimeHeaders));
            } catch (SOAPException e) {
                e.printStackTrace();
                log.warn("Could not store attachment in session key", e);
            }
            i++;
        }
        pipelineSession.put("attachments", attachments.toXML());

        // Transform SOAP message to string
        String message;
        try {
            message = XmlUtils.nodeToString(request.getSOAPPart());
            log.debug(getLogPrefix(correlationId) + "transforming from SOAP message");
        } catch (TransformerException e) {
            String m = "Could not transform SOAP message to string";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }

        // Process message via WebServiceListener
        ISecurityHandler securityHandler = new WebServiceContextSecurityHandler(webServiceContext);
        pipelineSession.setSecurityHandler(securityHandler);
        pipelineSession.put(IPipeLineSession.HTTP_REQUEST_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST));
        pipelineSession.put(IPipeLineSession.HTTP_RESPONSE_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE));

        try {
            log.debug(getLogPrefix(correlationId) + "processing message");
            result = processRequest(correlationId, message, pipelineSession);
        } catch (ListenerException e) {
            String m = "Could not process SOAP message: " + e.getMessage();
            log.error(m);
            throw new WebServiceException(m, e);
        }
    }

    // Transform result string to SOAP message
    SOAPMessage soapMessage = null;
    try {
        log.debug(getLogPrefix(correlationId) + "transforming to SOAP message");
        soapMessage = getMessageFactory().createMessage();
        StreamSource streamSource = new StreamSource(new StringReader(result));
        soapMessage.getSOAPPart().setContent(streamSource);
    } catch (SOAPException e) {
        String m = "Could not transform string to SOAP message";
        log.error(m);
        throw new WebServiceException(m, e);
    }

    String multipartXml = (String) pipelineSession.get(attachmentXmlSessionKey);
    log.debug(getLogPrefix(correlationId) + "building multipart message with MultipartXmlSessionKey ["
            + multipartXml + "]");
    if (StringUtils.isNotEmpty(multipartXml)) {
        Element partsElement;
        try {
            partsElement = XmlUtils.buildElement(multipartXml);
        } catch (DomBuilderException e) {
            String m = "error building multipart xml";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }
        Collection<Node> parts = XmlUtils.getChildTags(partsElement, "part");
        if (parts == null || parts.size() == 0) {
            log.warn(getLogPrefix(correlationId) + "no part(s) in multipart xml [" + multipartXml + "]");
        } else {
            Iterator<Node> iter = parts.iterator();
            while (iter.hasNext()) {
                Element partElement = (Element) iter.next();
                //String partType = partElement.getAttribute("type");
                String partName = partElement.getAttribute("name");
                String partSessionKey = partElement.getAttribute("sessionKey");
                String partMimeType = partElement.getAttribute("mimeType");
                Object partObject = pipelineSession.get(partSessionKey);
                if (partObject instanceof InputStream) {
                    InputStream fis = (InputStream) partObject;

                    DataHandler dataHander = null;
                    try {
                        dataHander = new DataHandler(new ByteArrayDataSource(fis, partMimeType));
                    } catch (IOException e) {
                        String m = "Unable to add session key '" + partSessionKey + "' as attachment";
                        log.error(m, e);
                        throw new WebServiceException(m, e);
                    }
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended filepart [" + partSessionKey
                            + "] with value [" + partObject + "] and name [" + partName + "]");
                } else { //String
                    String partValue = (String) partObject;

                    DataHandler dataHander = new DataHandler(new ByteArrayDataSource(partValue, partMimeType));
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended stringpart [" + partSessionKey
                            + "] with value [" + partValue + "]");
                }
            }
        }
    }

    return soapMessage;
}

From source file:org.apache.axis.handlers.HandlerChainImpl.java

public ArrayList getMessageInfo(SOAPMessage message) {
    ArrayList list = new ArrayList();
    try {//from w  ww  . jav a  2  s.c  om
        if (message == null || message.getSOAPPart() == null)
            return list;
        SOAPEnvelope env = message.getSOAPPart().getEnvelope();
        SOAPBody body = env.getBody();
        Iterator it = body.getChildElements();
        SOAPElement operation = (SOAPElement) it.next();
        list.add(operation.getElementName().toString());
        for (Iterator i = operation.getChildElements(); i.hasNext();) {
            SOAPElement elt = (SOAPElement) i.next();
            list.add(elt.getElementName().toString());
        }
    } catch (Exception e) {
        log.debug("Exception in getMessageInfo : ", e);
    }
    return list;
}

From source file:org.apache.axis.handlers.HandlerChainImpl.java

private void preInvoke(SOAPMessageContext msgContext) {
    try {/*from  w ww  . j  ava 2s .  co  m*/
        SOAPMessage message = msgContext.getMessage();
        // Ensure that message is already in the form we want 
        if (message != null && message.getSOAPPart() != null)
            message.getSOAPPart().getEnvelope();
        msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.FALSE);
        msgContext.setProperty(JAXRPC_METHOD_INFO, getMessageInfo(message));
    } catch (Exception e) {
        log.debug("Exception in preInvoke : ", e);
        throw new RuntimeException("Exception in preInvoke : " + e.toString());
    }
}

From source file:org.apache.axis2.jaxws.handler.SoapMessageContext.java

/**
 * Updates information about the SOAPMessage so that
 * we can determine later if it has changed
 * @param sm SOAPMessage// w  w  w.  ja  v a 2s .  com
 */
private void cacheSOAPMessageInfo(SOAPMessage sm) {
    cachedSoapPart = null;
    cachedSoapEnvelope = null;
    cachedAttachmentParts.clear();
    try {
        cachedSoapPart = sm.getSOAPPart();
        if (cachedSoapPart != null) {
            cachedSoapEnvelope = cachedSoapPart.getEnvelope();
        }
        if (sm.countAttachments() > 0) {
            Iterator it = sm.getAttachments();
            while (it != null && it.hasNext()) {
                AttachmentPart ap = (AttachmentPart) it.next();
                cachedAttachmentParts.add(ap);
            }
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring ", t);
        }
    }
}

From source file:org.apache.axis2.jaxws.handler.SoapMessageContext.java

/**
 * Checks the information in SOAPMessage sm against 
 * the information previously cached.  If an exception occurs
 * @param sm SOAPMessage/*  w  ww .  jav  a2  s  .c  o  m*/
 * @return true if match , (exceptions are interpeted as false)
 */
private boolean checkSOAPMessageInfo(SOAPMessage sm) {
    if (log.isDebugEnabled()) {
        log.debug("checkSOAPMessageInfo with " + JavaUtils.getObjectIdentity(sm));
    }
    // Check SOAPPart and SOAPEnvelope identity
    SOAPPart currentSoapPart = null;
    SOAPEnvelope currentSoapEnvelope = null;

    try {
        currentSoapPart = sm.getSOAPPart();
        if (currentSoapPart != null) {
            currentSoapEnvelope = cachedSoapPart.getEnvelope();
        }
        // Check object identity
        if (cachedSoapPart != currentSoapPart) {
            if (log.isDebugEnabled()) {
                log.debug("checkSOAPMessageInfo returns false due to: mismatched SOAPParts");
            }
            return false;
        }
        if (cachedSoapEnvelope != currentSoapEnvelope) {
            if (log.isDebugEnabled()) {
                log.debug("checkSOAPMessageInfo returns false due to: mismatched SOAPEnvelopes");
            }
            return false;
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("checkSOAPMessageInfo returns false due to: ", t);
        }
    }

    // Check AttachmentParts
    try {
        int currentNumAttachmentParts = sm.countAttachments();
        if (currentNumAttachmentParts != cachedAttachmentParts.size()) {
            if (log.isDebugEnabled()) {
                log.debug("checkSOAPMessageInfo returns false due to: "
                        + "current number of AttachmentParts is " + currentNumAttachmentParts
                        + " versus cached number is " + cachedAttachmentParts.size());
            }
            return false;
        }
        if (currentNumAttachmentParts > 0) {
            if (log.isDebugEnabled()) {
                log.debug("checkSOAPMessageInfo detected " + currentNumAttachmentParts + "AttachmentParts");
            }
            Iterator cachedIT = cachedAttachmentParts.iterator();
            Iterator currentIT = sm.getAttachments();
            while (currentIT.hasNext() && cachedIT.hasNext()) {
                AttachmentPart currentAP = (AttachmentPart) currentIT.next();
                AttachmentPart cachedAP = (AttachmentPart) cachedIT.next();
                if (currentAP != cachedAP) {
                    if (log.isDebugEnabled()) {
                        log.debug("checkSOAPMessageInfo returns false due to: " + "current AttachmentParts is "
                                + JavaUtils.getObjectIdentity(currentAP) + " and cached is "
                                + JavaUtils.getObjectIdentity(cachedAP));
                    }
                    return false;
                }
            }
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("checkSOAPMessageInfo returns false due to: ", t);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("checkSOAPMessageInfo returns true");
    }
    return true;
}

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

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

    // TODO: //from  w ww  .  j  a  v  a  2s .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);
    }

}