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:com.wandrell.example.swss.test.util.SoapMessageUtils.java

/**
 * Creates a {@code SOAPMessage} from the contents of a text file.
 * <p>//from  w  w  w .j a va  2 s . c o m
 * This file should contain a valid SOAP message.
 *
 * @param path
 *            the path to the file
 * @return a {@code SOAPMessage} parsed from the contents of the file
 * @throws SOAPException
 *             if there is any problem when generating the SOAP message
 * @throws IOException
 *             if there is any problem when reading the file
 */
public static final SOAPMessage getMessage(final String path) throws SOAPException, IOException {
    final MessageFactory factory; // Factory for generating the message
    final InputStream streamFile; // Stream for the file contents

    streamFile = new ClassPathResource(path).getInputStream();
    factory = MessageFactory.newInstance();

    return factory.createMessage(null, streamFile);
}

From source file:py.una.pol.karaku.test.test.services.KarakuFaultMessageResolverTest.java

/**
 * @return/* w  ww .j  ava  2 s  .co  m*/
 * @throws OPException
 * @throws Exception
 */
private SOAPMessage getFromString(String xml) throws Exception {

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

From source file:net.bpelunit.test.unit.TestSOAPEncoder.java

@Test
public void testDecodeDocLit() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage rcvMessage = factory.createMessage(null,
            this.getClass().getResourceAsStream(PATH_TO_FILES + "doclit2.xmlfrag"));
    SOAPOperationCallIdentifier operation = TestUtil.getCall(PATH_TO_FILES, PARTNER_WSDL, PARTNER_OPERATION,
            SOAPOperationDirectionIdentifier.INPUT);

    ISOAPEncoder encoder = new DocumentLiteralEncoder();
    Element parent = encoder.deconstruct(operation, rcvMessage);

    NamespaceContextImpl nsi = new NamespaceContextImpl();
    nsi.setNamespace("tns", "http://xxx");

    Node node = TestUtil.getNode(parent, nsi, "tns:about");
    assertNotNull(node);/*from  w w w . j a v a  2 s.  c om*/

    Node node2 = TestUtil.getNode(parent, nsi, "tns:about/tns:me");
    assertNotNull(node2);
}

From source file:net.bpelunit.test.unit.TestSOAPEncoder.java

@Test
public void testDecodeRPCLit() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage rcvMessage = factory.createMessage(null,
            this.getClass().getResourceAsStream(PATH_TO_FILES + "rpclit2.xmlfrag"));
    SOAPOperationCallIdentifier operation = TestUtil.getCall(PATH_TO_FILES, PARTNER_WSDL, PARTNER_OPERATION,
            SOAPOperationDirectionIdentifier.INPUT);

    ISOAPEncoder encoder = new RPCLiteralEncoder();
    Element parent = encoder.deconstruct(operation, rcvMessage);

    NamespaceContextImpl nsi = new NamespaceContextImpl();
    nsi.setNamespace("tns", "http://xxx");

    Node node = TestUtil.getNode(parent, nsi, "someFirstPart");
    assertNotNull(node);/*from  w w w .j  ava2s  . c om*/

    Node node2 = TestUtil.getNode(parent, nsi, "someFirstPart/tns:me");
    assertNotNull(node2);
}

From source file:ee.sk.hwcrypto.demo.controller.SigningController.java

private SOAPMessage SOAPQuery(String req) {
    try {//from  www .  ja  va  2 s .  c  o m
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        String url = "http://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl";

        MessageFactory messageFactory = MessageFactory.newInstance();
        InputStream is = new ByteArrayInputStream(req.getBytes());
        SOAPMessage soapMessage = messageFactory.createMessage(null, is);
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "https://www.openxades.org:8443/DigiDocService/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("", url);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", "");
        soapMessage.saveChanges();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, serverURI);

        return soapResponse;
    } catch (Exception e) {
        log.error("SOAP Exception " + e);
    }
    return null;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private Map<String, String> parseResponseXml(String expectedTagName, byte[] data) {
    try {//  w ww  . j a v a2  s .  c o  m
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(data));

        if (soapMessage.getSOAPBody().hasFault()) {
            StringWriter writer = new StringWriter();
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(writer));
            } catch (IllegalArgumentException | TransformerException | TransformerFactoryConfigurationError e) {
                writer.append("Failed to dump fault: " + e);
            }

            throw new ResponseException(writer.toString());
        }

        Iterator<SOAPBodyElement> responseBlockIt = soapMessage.getSOAPBody()
                .getChildElements(new QName(serviceType, expectedTagName));
        if (!responseBlockIt.hasNext()) {
            throw new ResponseException(expectedTagName + " tag missing");
        }

        Map<String, String> ret = new HashMap<>();

        SOAPBodyElement responseNode = responseBlockIt.next();
        Iterator<SOAPBodyElement> responseChildrenIt = responseNode.getChildElements();
        while (responseChildrenIt.hasNext()) {
            SOAPBodyElement param = responseChildrenIt.next();
            String name = StringUtils.trim(param.getLocalName().trim());
            String value = StringUtils.trim(param.getValue().trim());

            ret.put(name, value);
        }

        return ret;
    } catch (IllegalArgumentException | IOException | SOAPException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

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/*from w w w. ja v  a2  s.  co 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;
}

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

/**
 *     Create a SOAPMessage object from a InputStream to a SOAPMessage
 *     @param soapStream the InputStream to the SOAPMessage
 *     @return the created SOAPMessage//from  w ww  .  j  a va 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);

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

    return msg;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Assume that the InputStream has a SOAP fault message and return a String
 * suitable to present as an exception message
 *  //from  w w  w  .  ja va2  s.  c  o  m
 * @param is InputStream that contains a SOAP message
 * @return String containing a formated error message
 * 
 * @throws IOException
 * @throws SOAPException
 */
private String getSOAPFaultAsString(InputStream is) throws IOException, SOAPException {
    is.reset();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage(null, is);
    SOAPBody body = message.getSOAPBody();

    if (body.hasFault()) {
        SOAPFault fault = body.getFault();
        String code, string, actor;
        code = fault.getFaultCode();
        string = fault.getFaultString();
        actor = fault.getFaultActor();
        String formatedMessage = "SOAP transaction resulted in a SOAP fault.";

        if (code != null)
            formatedMessage += "  Code=\"" + code + ".\"";

        if (string != null)
            formatedMessage += "  String=\"" + string + ".\"";

        if (actor != null)
            formatedMessage += "  Actor=\"" + actor + ".\"";

        return formatedMessage;
    }
    return null;
}

From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CodeTimer timer = new CodeTimer("SoapServlet.doPost()", true);

    InputStream reqInputStream = request.getInputStream();
    // read the POST request contents
    String requestString = getRequestString(request);
    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener POST Request:\n" + requestString);
    }/*from   w  w  w . j  a  v  a  2 s . c  o m*/

    Map<String, String> metaInfo = buildMetaInfo(request);

    String responseString = null;
    MessageFactory factory = null;
    String soapVersion = SOAPConstants.SOAP_1_1_PROTOCOL;
    try {
        SOAPMessage message = null;
        SOAPBody body = null;
        try {
            // Intuitively guess which SOAP version is needed
            // factory = getMessageFactory(requestString, true);
            soapVersion = getSoapVersion(requestString, true);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
        } catch (SOAPException e) {
            // Unlikely, but just in case the SOAP version guessing
            // has guessed incorrectly, this catches any SOAP exception,
            // in which case try the other version
            if (logger.isMdwDebugEnabled()) {
                logger.mdwDebug(
                        "SOAPListenerServlet failed to find correct Message Factory:" + "\n" + e.getMessage());
            }
            // Try with the other unintuitive MessageFactory
            // factory = getMessageFactory(requestString, false);
            soapVersion = getSoapVersion(requestString, false);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
            // Only 2 versions, so let any exceptions bubble up
        }
        Node childElem = null;
        Iterator<?> it = body.getChildElements();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                childElem = node;
                break;
            }
        }
        if (childElem == null)
            throw new SOAPException("SOAP body child element not found");

        String requestXml = null;

        boolean oldStyleRpcRequest = false;
        if (request.getServletPath().endsWith(RPC_SERVICE_PATH)
                || RPC_SERVICE_PATH.equals(request.getPathInfo())) {
            NodeList nodes = childElem.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                if (StringUtils.isNotBlank(nodes.item(i).getNodeName())
                        && nodes.item(i).getNodeName().equals("RequestDetails")) {
                    oldStyleRpcRequest = true;
                    Node requestNode = nodes.item(i).getFirstChild();
                    if (requestNode.getNodeType() == Node.CDATA_SECTION_NODE) {
                        requestXml = requestNode.getTextContent();
                    } else {
                        requestXml = DomHelper.toXml(requestNode);
                        if (requestXml.contains("&lt;"))
                            requestXml = StringEscapeUtils.unescapeXml(requestXml);
                    }
                }
            }
        } else {
            requestXml = DomHelper.toXml(childElem);
        }

        metaInfo = addSoapMetaInfo(metaInfo, message);
        ListenerHelper helper = new ListenerHelper();

        try {
            authenticate(request, metaInfo, requestXml);
            String handlerResponse = helper.processEvent(requestXml, metaInfo);

            try {
                // standard response indicates a potential problem
                MDWStatusMessageDocument responseDoc = MDWStatusMessageDocument.Factory.parse(handlerResponse,
                        Compatibility.namespaceOptions());
                MDWStatusMessage responseMsg = responseDoc.getMDWStatusMessage();
                if ("SUCCESS".equals(responseMsg.getStatusMessage()))
                    responseString = createSoapResponse(soapVersion, handlerResponse);
                else
                    responseString = createSoapFaultResponse(soapVersion,
                            String.valueOf(responseMsg.getStatusCode()), responseMsg.getStatusMessage());
            } catch (XmlException xex) {
                if (Listener.METAINFO_ERROR_RESPONSE_VALUE
                        .equalsIgnoreCase(metaInfo.get(Listener.METAINFO_ERROR_RESPONSE))) {
                    // Support for custom error response
                    responseString = handlerResponse;
                } else {
                    // not parseable as standard response doc (a good thing)
                    if (oldStyleRpcRequest) {
                        responseString = createOldStyleSoapResponse(soapVersion,
                                "<m:invokeWebServiceResponse xmlns:m=\"http://mdw.qwest.com/listener/webservice\"><Response>"
                                        + StringEscapeUtils.escapeXml(handlerResponse)
                                        + "</Response></m:invokeWebServiceResponse>");
                    } else {
                        responseString = createSoapResponse(soapVersion, handlerResponse);
                    }
                }
            }
        } catch (ServiceException ex) {
            logger.severeException(ex.getMessage(), ex);
            responseString = createSoapFaultResponse(soapVersion, String.valueOf(ex.getCode()),
                    ex.getMessage());
        }
    } catch (Exception ex) {
        logger.severeException(ex.getMessage(), ex);
        try {
            responseString = createSoapFaultResponse(soapVersion, null, ex.getMessage());
        } catch (Exception tex) {
            logger.severeException(tex.getMessage(), tex);
        }
    }

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener Servlet POST Response:\n" + responseString);
    }

    if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) != null) {
        response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE));
    } else {
        if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL))
            response.setContentType(Listener.CONTENT_TYPE_XML);
        else
            response.setContentType("application/soap+xml");
    }

    response.getOutputStream().print(responseString);

    timer.stopAndLogTiming("");
}