Example usage for javax.xml.soap MessageFactory createMessage

List of usage examples for javax.xml.soap MessageFactory createMessage

Introduction

In this page you can find the example usage for javax.xml.soap MessageFactory createMessage.

Prototype

public abstract SOAPMessage createMessage(MimeHeaders headers, InputStream in)
        throws IOException, SOAPException;

Source Link

Document

Internalizes the contents of the given InputStream object into a new SOAPMessage object and returns the SOAPMessage object.

Usage

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

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

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

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

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

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

        byte[] bytes = outStream.toByteArray();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

From source file:org.belio.service.gateway.SafcomGateway.java

private static SOAPMessage getSoapMessageFromString(String xml) throws SOAPException, IOException {
    MessageFactory factory = MessageFactory.newInstance();
    javax.xml.soap.SOAPMessage message = factory.createMessage(new MimeHeaders(),
            new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))));
    return message;
}

From source file:org.cerberus.service.soap.impl.SoapService.java

@Override
public SOAPMessage createSoapRequest(String envelope, String method)
        throws SOAPException, IOException, SAXException, ParserConfigurationException {
    String unescapedEnvelope = StringEscapeUtils.unescapeXml(envelope);
    boolean is12SoapVersion = SOAP_1_2_NAMESPACE_PATTERN.matcher(unescapedEnvelope).matches();

    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("SOAPAction", "\"" + method + "\"");
    headers.addHeader("Content-Type",
            is12SoapVersion ? SOAPConstants.SOAP_1_2_CONTENT_TYPE : SOAPConstants.SOAP_1_1_CONTENT_TYPE);

    InputStream input = new ByteArrayInputStream(unescapedEnvelope.getBytes("UTF-8"));
    MessageFactory messageFactory = MessageFactory
            .newInstance(is12SoapVersion ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL);
    return messageFactory.createMessage(headers, input);
}

From source file:org.eevolution.LMX.engine.vendor.LMXFoliosDigitalesService.java

public String getXMLSealed(final String respxml) throws AdempiereException, IOException, SOAPException {

    String[] respuesta = null;//  w w w .ja va  2 s .  c om

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage(new MimeHeaders(),
            new ByteArrayInputStream(respxml.getBytes(Charset.forName("UTF-8"))));

    SOAPBody body = message.getSOAPBody();
    NodeList returnList = body.getElementsByTagName("TimbrarPruebaCFDIResult");
    NodeList innerRes = returnList.item(0).getChildNodes();

    boolean failed = false;

    respuesta = new String[innerRes.getLength()];
    String messageError = null;

    for (int i = 0; i < innerRes.getLength(); i++) {
        respuesta[i] = innerRes.item(i).getTextContent();

        if (i < 3 && !respuesta[i].equals("")) {
            failed = true;
            messageError = respuesta[i];
            //System.out.println(messageError);
        }
    }

    if (failed)
        throw new AdempiereException(messageError);

    respuesta[3] = StringEscapeUtils.unescapeXml(respuesta[3]);
    return respuesta[3];
}

From source file:org.freebxml.omar.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.j  a  v  a 2  s .  c o m*/
 */
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);

    msg.saveChanges();

    return msg;
}

From source file:org.springframework.ws.soap.saaj.support.SaajUtils.java

/**
 * Loads a SAAJ <code>SOAPMessage</code> from the given resource with a given message factory.
 *
 * @param resource       the resource to read from
 * @param messageFactory SAAJ message factory used to construct the message
 * @return the loaded SAAJ message/*from   w  w w. j a va2 s  .  c o  m*/
 * @throws SOAPException if the message cannot be constructed
 * @throws IOException   if the input stream resource cannot be loaded
 */
public static SOAPMessage loadMessage(Resource resource, MessageFactory messageFactory)
        throws SOAPException, IOException {
    InputStream is = resource.getInputStream();
    try {
        MimeHeaders mimeHeaders = new MimeHeaders();
        mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_TYPE, "text/xml");
        mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_LENGTH,
                Long.toString(resource.getFile().length()));
        return messageFactory.createMessage(mimeHeaders, is);
    } finally {
        is.close();
    }
}

From source file:org.wso2.caching.receivers.CacheMessageReceiver.java

/**
 * This method will be called when the message is received to the MR
 * and this will serve the response from the cache
 *
 * @param messageCtx - MessageContext to be served
 * @throws AxisFault if there is any error in serving from the cache
 *///w  w  w.j a  va  2 s . co  m
public void receive(MessageContext messageCtx) throws AxisFault {

    MessageContext outMsgContext = MessageContextBuilder.createOutMessageContext(messageCtx);

    if (outMsgContext != null) {
        OperationContext opCtx = outMsgContext.getOperationContext();

        if (opCtx != null) {
            opCtx.addMessageContext(outMsgContext);
            if (log.isDebugEnabled()) {
                log.debug("Serving from the cache...");
            }

            Object cachedObj = opCtx.getPropertyNonReplicable(CachingConstants.CACHED_OBJECT);
            if (cachedObj != null && cachedObj instanceof CachableResponse) {
                try {
                    MessageFactory mf = MessageFactory.newInstance();
                    SOAPMessage smsg;
                    if (messageCtx.isSOAP11()) {
                        smsg = mf.createMessage(new MimeHeaders(),
                                new ByteArrayInputStream(((CachableResponse) cachedObj).getResponseEnvelope()));
                        ((CachableResponse) cachedObj).setInUse(false);
                    } else {
                        MimeHeaders mimeHeaders = new MimeHeaders();
                        mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
                        mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
                        smsg = mf.createMessage(mimeHeaders,
                                new ByteArrayInputStream(((CachableResponse) cachedObj).getResponseEnvelope()));
                        ((CachableResponse) cachedObj).setInUse(false);
                    }

                    if (smsg != null) {
                        org.apache.axiom.soap.SOAPEnvelope omSOAPEnv = SAAJUtil
                                .toOMSOAPEnvelope(smsg.getSOAPPart().getDocumentElement());
                        if (omSOAPEnv.getHeader() == null) {
                            SOAPFactory fac = getSOAPFactory(messageCtx);
                            fac.createSOAPHeader(omSOAPEnv);
                        }
                        outMsgContext.setEnvelope(omSOAPEnv);
                    } else {
                        handleException("Unable to serve from the cache : "
                                + "Couldn't build the SOAP response from the cached byte stream");
                    }

                } catch (SOAPException e) {
                    handleException("Unable to serve from the cache : "
                            + "Unable to get build the response from the byte stream", e);
                } catch (IOException e) {
                    handleException("Unable to serve from the cache : "
                            + "I/O Error in building the response envelope from the byte stream");
                }

                AxisEngine.send(outMsgContext);

            } else {
                handleException("Unable to find the response in the cache");
            }
        } else {
            handleException("Unable to serve from " + "the cache : OperationContext not found for processing");
        }
    } else {
        handleException("Unable to serve from " + "the cache : Unable to get the out message context");
    }
}

From source file:org.wso2.carbon.caching.module.receivers.CacheMessageReceiver.java

/**
 * This method will be called when the message is received to the MR
 * and this will serve the response from the cache
 *
 * @param messageCtx - MessageContext to be served
 * @throws AxisFault if there is any error in serving from the cache
 *///from   w ww .  j a v  a2  s .  co  m
public void receive(MessageContext messageCtx) throws AxisFault {

    MessageContext outMsgContext = MessageContextBuilder.createOutMessageContext(messageCtx);

    if (outMsgContext != null) {
        OperationContext opCtx = outMsgContext.getOperationContext();

        if (opCtx != null) {
            opCtx.addMessageContext(outMsgContext);
            if (log.isDebugEnabled()) {
                log.debug("Serving from the cache...");
            }

            Object cachedObj = opCtx.getPropertyNonReplicable(CachingConstants.CACHED_OBJECT);
            /**
             * This was introduced to  avoid cache being expired before this below code executed.
             */
            byte[] bt = (byte[]) opCtx.getPropertyNonReplicable(CachingConstants.CACHEENVELOPE);

            if (bt != null) {
                try {
                    MessageFactory mf = MessageFactory.newInstance();
                    SOAPMessage smsg;
                    if (messageCtx.isSOAP11()) {
                        smsg = mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(bt));
                        ((CachableResponse) cachedObj).setInUse(false);
                    } else {
                        MimeHeaders mimeHeaders = new MimeHeaders();
                        mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
                        mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
                        smsg = mf.createMessage(mimeHeaders, new ByteArrayInputStream(bt));
                        ((CachableResponse) cachedObj).setInUse(false);
                    }

                    if (smsg != null) {
                        org.apache.axiom.soap.SOAPEnvelope omSOAPEnv = SAAJUtil
                                .toOMSOAPEnvelope(smsg.getSOAPPart().getDocumentElement());
                        if (omSOAPEnv.getHeader() == null) {
                            SOAPFactory fac = getSOAPFactory(messageCtx);
                            fac.createSOAPHeader(omSOAPEnv);
                        }
                        outMsgContext.setEnvelope(omSOAPEnv);
                    } else {
                        handleException("Unable to serve from the cache : "
                                + "Couldn't build the SOAP response from the cached byte stream");
                    }

                } catch (SOAPException e) {
                    handleException("Unable to serve from the cache : "
                            + "Unable to get build the response from the byte stream", e);
                } catch (IOException e) {
                    handleException("Unable to serve from the cache : "
                            + "I/O Error in building the response envelope from the byte stream");
                }

                AxisEngine.send(outMsgContext);

            } else {
                handleException("Unable to find the response in the cache");
            }
        } else {
            handleException("Unable to serve from " + "the cache : OperationContext not found for processing");
        }
    } else {
        handleException("Unable to serve from " + "the cache : Unable to get the out message context");
    }
}

From source file:org.wso2.carbon.identity.sso.saml.servlet.SAMLArtifactResolveServlet.java

/**
 * All requests are handled by this handleRequest method. Request should come with a soap envelop that
 * wraps an ArtifactResolve object. First we try to extract resolve object and if successful, call
 * handle artifact method.//from w  ww  .  j a  v a 2  s  .co m
 *
 * @param req  HttpServletRequest object received.
 * @param resp HttpServletResponse object to be sent.
 * @throws ServletException
 * @throws IOException
 */
private void handleRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    try {
        ArtifactResolve artifactResolve = null;
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            InputStream inStream = req.getInputStream();
            SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), inStream);
            if (log.isDebugEnabled()) {
                OutputStream outputStream = new ByteArrayOutputStream();
                soapMessage.writeTo(outputStream);
                log.debug("SAML2 Artifact Resolve request received: " + outputStream.toString());
            }
            SOAPBody soapBody = soapMessage.getSOAPBody();
            Iterator iterator = soapBody.getChildElements();

            while (iterator.hasNext()) {
                SOAPBodyElement artifactResolveElement = (SOAPBodyElement) iterator.next();

                if (StringUtils.equals(SAMLConstants.SAML20P_NS, artifactResolveElement.getNamespaceURI())
                        && StringUtils.equals(ArtifactResolve.DEFAULT_ELEMENT_LOCAL_NAME,
                                artifactResolveElement.getLocalName())) {

                    DOMSource source = new DOMSource(artifactResolveElement);
                    StringWriter stringResult = new StringWriter();
                    TransformerFactory.newInstance().newTransformer().transform(source,
                            new StreamResult(stringResult));
                    artifactResolve = (ArtifactResolve) SAMLSSOUtil.unmarshall(stringResult.toString());
                }
            }
        } catch (SOAPException e) {
            throw new ServletException("Error while extracting SOAP body from the request.", e);
        } catch (TransformerException e) {
            throw new ServletException("Error while extracting ArtifactResponse from the request.", e);
        } catch (IdentityException e) {
            throw new ServletException("Error while unmarshalling ArtifactResponse  from the request.", e);
        }

        if (artifactResolve != null) {
            handleArtifact(req, resp, artifactResolve);
        } else {
            log.error("Invalid SAML Artifact Resolve request received.");
        }

    } finally {
        SAMLSSOUtil.removeSaaSApplicationThreaLocal();
        SAMLSSOUtil.removeUserTenantDomainThreaLocal();
        SAMLSSOUtil.removeTenantDomainFromThreadLocal();
    }
}

From source file:org.wso2.carbon.identity.sso.saml.servlet.SAMLECPProviderServlet.java

/**
 * This method returns s SOAP message from the given Servlet Input Stream.
 * @param inputStream InputStream from the servlet Request
 * @return//from w  w w. j  a v a  2 s. c  o  m
 * @throws IOException
 * @throws SOAPException
 */
private SOAPMessage createSOAPMessagefromInputStream(InputStream inputStream)
        throws SOAPException, IOException {
    SOAPMessage soapMessage;
    MessageFactory messageFactory = MessageFactory.newInstance();
    soapMessage = messageFactory.createMessage(new MimeHeaders(), inputStream);
    return soapMessage;
}