Example usage for javax.xml.soap SOAPConstants SOAP_1_1_PROTOCOL

List of usage examples for javax.xml.soap SOAPConstants SOAP_1_1_PROTOCOL

Introduction

In this page you can find the example usage for javax.xml.soap SOAPConstants SOAP_1_1_PROTOCOL.

Prototype

String SOAP_1_1_PROTOCOL

To view the source code for javax.xml.soap SOAPConstants SOAP_1_1_PROTOCOL.

Click Source Link

Document

Used to create MessageFactory instances that create SOAPMessages whose behavior supports the SOAP 1.1 specification.

Usage

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 ww  w. j ava  2  s. com

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

From source file:io.hummer.util.ws.WebServiceClient.java

public InvocationResult invoke(InvocationRequest request, int retries) throws Exception {

    Map<String, String> httpHeaders = extractHeaders(request.httpHeaders);
    int connectTimeoutMS = CONNECT_TIMEOUT_MS;
    int requestTimeoutMS = request.timeout ? READ_TIMEOUT_MS : READ_TIMEOUT_VERYLONG_MS;
    if (request.body != null) {
        if (request.type == RequestType.SOAP || request.type == RequestType.SOAP11) {
            try {
                return doInvokeSOAP((Element) request.getBodyAsElement(), request.soapHeaders, retries,
                        SOAPConstants.SOAP_1_1_PROTOCOL, connectTimeoutMS, requestTimeoutMS);
            } catch (Exception e) {
                logger.debug("SOAP invocation failed: " + new ExceptionsUtil().getAllCauses(e));
                throw e;
            }/*from  w w  w. j  a  v  a  2s. c  om*/
        }
        if (request.type == RequestType.SOAP12) {
            try {
                return doInvokeSOAP((Element) request.getBodyAsElement(), request.soapHeaders, retries,
                        SOAPConstants.SOAP_1_2_PROTOCOL, connectTimeoutMS, requestTimeoutMS);
            } catch (Exception e) {
                throw e;
            }
        } else if (request.type == RequestType.HTTP_GET) {
            requestTimeoutMS = request.timeout ? READ_TIMEOUT_HTTP_GET_MS : READ_TIMEOUT_HTTP_GET_VERYLONG_MS;
            if (logger.isDebugEnabled())
                logger.debug("Request body: " + request.body);
            Object c = request.body;
            if (!(c instanceof String) && c != null) {
                logger.warn("Unexpected tyle " + c.getClass() + " of input body content: ");
                if (c instanceof Element) {
                    xmlUtil.print((Element) c);
                } else {
                    System.out.println(c);
                }
            }
            return doInvokeGET((String) c, httpHeaders, retries, connectTimeoutMS, requestTimeoutMS,
                    request.cache);
        } else if (request.type == RequestType.HTTP_POST)
            return doInvokePOST(request.body, httpHeaders, retries);
    } else {
        requestTimeoutMS = request.timeout ? READ_TIMEOUT_HTTP_GET_MS : READ_TIMEOUT_HTTP_GET_VERYLONG_MS;
        return doInvokeGET("", httpHeaders, retries, connectTimeoutMS, requestTimeoutMS, request.cache);
    }
    return null;
}

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

/**
 * <p>/*from w w w . j a va 2s. c  o  m*/
 * Gives a hint as to which version of SOAP using the rudimentary check
 * below. If the hint fails, it'll try the other version anyway.
 * </p>
 * <ul>
 * <li>SOAP 1.1 : http://schemas.xmlsoap.org/soap/envelope/</li>
 * <li>SOAP 1.2 : http://www.w3.org/2003/05/soap-envelope</li>
 * </ul>
 * <p>
 * This is on a per-request basis and can't be static since we need to
 * support SOAP 1.1 and 1.2
 * </p>
 *
 * @param requestString
 * @param goodguess
 * @return SOAP version 1 or 2
 * @throws IOException
 * @throws SOAPException
 */
private String getSoapVersion(String requestString, boolean goodguess) {

    String guessedVersion = SOAPConstants.SOAP_1_1_PROTOCOL;
    String otherVersion = SOAPConstants.SOAP_1_2_PROTOCOL;
    if (requestString.contains(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE)) {
        guessedVersion = SOAPConstants.SOAP_1_2_PROTOCOL;
        otherVersion = SOAPConstants.SOAP_1_1_PROTOCOL;
    }
    return goodguess ? guessedVersion : otherVersion;

}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private SOAPMessage prepareRequestEnvelope(String xmlFile, String wrapperElement)
        throws SOAPException, DOMException, IOException, SAXException, ParserConfigurationException {
    MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
    SOAPMessage reqMsg = mf.createMessage();
    SOAPPart part = reqMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();

    SOAPElement operation = body.addChildElement(wrapperElement, "stud", SERVICE_NS);
    operation.appendChild(env.getOwnerDocument().importNode(getSOAPBodyFromXML(xmlFile), true));
    reqMsg.saveChanges();/*ww  w . ja  va 2s  . c  om*/
    return reqMsg;
}

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

/**
 * Original API (Defaults to using MessageFactory.newInstance(), i.e. SOAP
 * 1.1)//www.j  a  v  a2s  .  c om
 *
 * @param message
 * @return Soap fault as string
 * @throws SOAPException
 * @throws TransformerException
 */
protected String createSoapFaultResponse(String message) throws SOAPException, TransformerException {
    return createSoapFaultResponse(SOAPConstants.SOAP_1_1_PROTOCOL, null, message);
}

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

/**
 * Original API (Defaults to using MessageFactory.newInstance(), i.e. SOAP
 * 1.1)/*from w  w w  .  j  a  va 2s .c o  m*/
 *
 * @param code
 * @param message
 * @return Soap fault as string
 * @throws SOAPException
 * @throws TransformerException
 */
protected String createSoapFaultResponse(String code, String message)
        throws SOAPException, TransformerException {
    return createSoapFaultResponse(SOAPConstants.SOAP_1_1_PROTOCOL, code, message);
}

From source file:io.hummer.util.ws.WebServiceClient.java

private SOAPMessage createSOAPMessage(Element request, List<Element> headers, String protocol)
        throws Exception {
    MessageFactory mf = MessageFactory.newInstance(protocol);
    SOAPMessage message = mf.createMessage();
    SOAPBody body = message.getSOAPBody();

    // check if we have a complete soap:Envelope as request..
    String ns = request.getNamespaceURI();
    if (request.getTagName().contains("Envelope")) {
        if (ns.equals("http://schemas.xmlsoap.org/soap/envelope/"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));
        if (ns.equals("http://www.w3.org/2003/05/soap-envelope"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));

    } else {//  w  w  w  .  ja va2  s  .  co m
        xmlUtil.appendChild(body, request);
    }
    for (Element h : headers) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    for (Element h : eprParamsAndProps) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    xmlUtil.appendChild(message.getSOAPHeader(), xmlUtil.toElement(
            "<wsa:To xmlns:wsa=\"" + EndpointReference.NS_WS_ADDRESSING + "\">" + endpointURL + "</wsa:To>"));
    message.saveChanges();
    return message;
}

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

/**
 * Allow version specific factory passed in to support SOAP 1.1 and 1.2
 * <b>Important</b> Faults are treated differently for 1.1 and 1.2 For 1.2
 * you can't use the elementName otherwise it throws an exception
 *
 * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
 *
 * @param factory/*from  w  w  w. j  av a  2s .com*/
 * @param code
 * @param message
 * @return Xml fault string
 * @throws SOAPException
 * @throws TransformerException
 */
protected String createSoapFaultResponse(String soapVersion, String code, String message)
        throws SOAPException, TransformerException {

    SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage();
    SOAPBody soapBody = soapMessage.getSOAPBody();
    /**
     * Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use
     * the elementName otherwise it throws an exception
     *
     * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
     */
    SOAPFault fault = null;
    if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) {
        // existing 1.1 functionality
        fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message);
        if (code != null)
            fault.setFaultCode(code);
    } else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) {
        /**
         * For 1.2 there are only a set number of allowed codes, so we can't
         * just use any one like what we did in 1.1. The recommended one to
         * use is SOAPConstants.SOAP_RECEIVER_FAULT
         */
        fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT,
                code == null ? message : code + " : " + message);

    }
    return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement());

}

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

/**
 * Original API (Defaults to using MessageFactory.newInstance(), i.e. SOAP
 * 1.1)//from  w  w  w  . jav  a  2 s  .c o  m
 *
 * @param xml
 * @return
 * @throws SOAPException
 */
protected String createSoapResponse(String xml) throws SOAPException {
    return createSoapResponse(SOAPConstants.SOAP_1_1_PROTOCOL, xml);
}

From source file:com.ibm.soatf.component.soap.SOAPComponent.java

private void checkSOAPMessage(boolean ok) throws SoapComponentException {
    ProgressMonitor.init(2, "Loading message from file...");
    String filename = new StringBuilder(serviceName).append(NAME_DELIMITER).append(operationName)
            .append(NAME_DELIMITER).append(RESPONSE_FILE_SUFFIX).toString();
    final File file = new File(workingDir, filename);
    InputStream is = null;//from w  w  w . j  ava2 s  .  co m
    try {
        final byte[] xmlMessage = FileUtils.readFileToByteArray(file);
        is = new ByteArrayInputStream(xmlMessage);
        SOAPMessage response = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)
                .createMessage(new MimeHeaders(), is);
        ProgressMonitor.increment("Checking for fault...");
        response.removeAllAttachments();
        SOAPEnvelope envp = response.getSOAPPart().getEnvelope();
        SOAPBody someBody = envp.getBody();
        if (ok) {
            if (someBody.getFault() == null) {
                cor.addMsg("soap body is OK");
                cor.markSuccessful();
            } else {
                final String msg = "found soap fault in response body:\n" + new String(xmlMessage);
                cor.addMsg(msg);
                throw new SoapComponentException(msg);
            }
        } else {
            if (someBody.getFault() != null) {
                cor.addMsg("found soap fault in response body");
                cor.markSuccessful();
            } else {
                final String msg = "response body doesn't contain soap fault:\n" + new String(xmlMessage);
                cor.addMsg(msg);
                throw new SoapComponentException(msg);
            }
        }
    } catch (IOException | SOAPException ex) {
        throw new SoapComponentException("error while trying to parse response", ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                logger.debug("Not able to close input stream. ", ex);
            }
        }
    }
}