Example usage for javax.xml.soap SOAPHeaderElement getElementName

List of usage examples for javax.xml.soap SOAPHeaderElement getElementName

Introduction

In this page you can find the example usage for javax.xml.soap SOAPHeaderElement getElementName.

Prototype

public Name getElementName();

Source Link

Document

Returns the name of this SOAPElement object.

Usage

From source file:ee.ria.xroad.proxy.testsuite.testcases.SplitHeaderMessage.java

@SuppressWarnings("unchecked")
private static void validateFieldValue(Message message) throws Exception {
    SoapMessageImpl msg = (SoapMessageImpl) new SoapParserImpl().parse(message.getContentType(),
            new ByteArrayInputStream(((SoapMessageImpl) message.getSoap()).getBytes()));
    String value = null;//from w  ww.  j a  v a 2s. c  o m
    Iterator<SOAPHeaderElement> h = msg.getSoap().getSOAPHeader().examineAllHeaderElements();
    while (h.hasNext()) {
        SOAPHeaderElement header = h.next();
        if (header.getElementName().getLocalName().equals("issue")) {
            value = header.getValue();
        }
    }
    if (!StringUtils.equals(EXPECTED_VALUE, value)) {
        String diff = StringUtils.difference(EXPECTED_VALUE, value);
        throw new Exception(
                "Unexpected field value (difference starting at" + " index : " + value.indexOf(diff) + ")");
    }
}

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

private SOAPMessage createFaultSOAPMessage(java.lang.Throwable e, SOAPHeader sh) {
    SOAPMessage msg = null;//from  w ww  .  j a va2 s  .c om
    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.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 w  w w .  j  av a 2s.  c o  m*/
 */

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:org.apache.ws.security.handler.WSS4JHandler.java

/**
 * handle responses/* w  ww .j ava2 s  . co  m*/
 *
 * @param mc
 * @param reqData
 * @return true on successful processing
 * @throws WSSecurityException
 */
public boolean doReceiver(MessageContext mc, RequestData reqData, boolean isRequest)
        throws WSSecurityException {

    Vector actions = new Vector();
    String action = (String) getOption(WSHandlerConstants.RECEIVE + '.' + WSHandlerConstants.ACTION);
    if (action == null) {
        action = (String) getOption(WSHandlerConstants.ACTION);
        if (action == null) {
            action = (String) mc.getProperty(WSHandlerConstants.ACTION);
        }
    }
    if (action == null) {
        throw new JAXRPCException("WSS4JHandler: No action defined");
    }
    int doAction = WSSecurityUtil.decodeAction(action, actions);

    String actor = (String) getOption(WSHandlerConstants.ACTOR);

    SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
    SOAPPart sPart = message.getSOAPPart();
    Document doc = null;
    try {
        doc = messageToDocument(message);
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot convert into document", ex);
    }
    /*
    * Check if it's a fault. Don't process faults.
    *
    */
    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
    if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) {
        return false;
    }

    /*
    * To check a UsernameToken or to decrypt an encrypted message we need
    * a password.
    */
    CallbackHandler cbHandler = null;
    if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) {
        cbHandler = getPasswordCB(reqData);
    }

    /*
    * Get and check the Signature specific parameters first because they
    * may be used for encryption too.
    */
    doReceiverAction(doAction, reqData);

    Vector wsResult = null;
    try {
        wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(),
                reqData.getDecCrypto());
    } catch (WSSecurityException ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: security processing failed", ex);
    }
    if (wsResult == null) { // no security header found
        if (doAction == WSConstants.NO_SECURITY) {
            return true;
        } else {
            throw new JAXRPCException("WSS4JHandler: Request does not contain required Security header");
        }
    }
    if (reqData.getWssConfig().isEnableSignatureConfirmation() && !isRequest) {
        checkSignatureConfirmation(reqData, wsResult);
    }

    /*
    * If we had some security processing, get the original
    * SOAP part of Axis' message and replace it with new SOAP
    * part. This new part may contain decrypted elements.
    */

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLUtils.outputDOM(doc, os, true);
    try {
        sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray())));
    } catch (SOAPException se) {
        if (doDebug) {
            log.debug(se.getMessage(), se);
        }
        throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se);
    }

    if (doDebug) {
        log.debug("Processed received SOAP request");
    }

    /*
    * After setting the new current message, probably modified because
    * of decryption, we need to locate the security header. That is,
    * we force Axis (with getSOAPEnvelope()) to parse the string, build
    * the new header. Then we examine, look up the security header
    * and set the header as processed.
    *
    * Please note: find all header elements that contain the same
    * actor that was given to processSecurityHeader(). Then
    * check if there is a security header with this actor.
    */

    SOAPHeader sHeader = null;
    try {
        sHeader = message.getSOAPPart().getEnvelope().getHeader();
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot get SOAP header after security processing", ex);
    }

    Iterator headers = sHeader.examineHeaderElements(actor);

    SOAPHeaderElement headerElement = null;
    while (headers.hasNext()) {
        SOAPHeaderElement hE = (SOAPHeaderElement) headers.next();
        if (hE.getElementName().getLocalName().equals(WSConstants.WSSE_LN)
                && ((Node) hE).getNamespaceURI().equals(WSConstants.WSSE_NS)) {
            headerElement = hE;
            break;
        }
    }

    /* JAXRPC conversion changes */
    headerElement.setMustUnderstand(false); // is this sufficient?

    /*
    * Now we can check the certificate used to sign the message.
    * In the following implementation the certificate is only trusted
    * if either it itself or the certificate of the issuer is installed
    * in the keystore.
    *
    * Note: the method verifyTrust(X509Certificate) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the signature action result from the action vector

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN);

    if (actionResult != null) {
        X509Certificate returnCert = (X509Certificate) actionResult
                .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

        if (returnCert != null && !verifyTrust(returnCert, reqData)) {
            throw new JAXRPCException("WSS4JHandler: The certificate used for the signature is not trusted");
        }
    }

    /*
    * Perform further checks on the timestamp that was transmitted in the header.
    * In the following implementation the timestamp is valid if it was
    * created after (now-ttl), where ttl is set on server side, not by the client.
    *
    * Note: the method verifyTimestamp(Timestamp) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the timestamp action result from the action vector
    actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);

    if (actionResult != null) {
        Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);

        if (timestamp != null && reqData.getWssConfig().isTimeStampStrict()
                && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
            throw new JAXRPCException("WSS4JHandler: The timestamp could not be validated");
        }
    }

    /*
    * now check the security actions: do they match, in right order?
    */
    if (!checkReceiverResults(wsResult, actions)) {
        throw new JAXRPCException("WSS4JHandler: security processing failed (actions mismatch)");
    }

    /*
    * All ok up to this point. Now construct and setup the
    * security result structure. The service may fetch this
    * and check it.
    */
    Vector results = null;
    if ((results = (Vector) mc.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {
        results = new Vector();
        mc.setProperty(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
    results.add(0, rResult);
    if (doDebug) {
        log.debug("WSS4JHandler: exit invoke()");
    }

    return true;
}

From source file:xsul.dsig.globus.security.authentication.wssec.WSSecurityUtil.java

/**
 * Returns first WS-Security header for a given actor.
 * Only one WS-Security header is allowed for an actor.
 *///from  www .  j a  v a  2s . co m
public static SOAPHeaderElement getSecurityHeader(SOAPEnvelope env, String actor) throws SOAPException {
    SOAPHeader header = env.getHeader();

    if (header == null) {
        return null;
    }

    Iterator headerElements = header.examineHeaderElements(actor);

    while (headerElements.hasNext()) {
        SOAPHeaderElement he = (SOAPHeaderElement) headerElements.next();
        Name nm = he.getElementName();

        // find ws-security header
        if (nm.getLocalName().equalsIgnoreCase(WSConstants.WS_SEC_LN)
                && nm.getURI().equalsIgnoreCase(WSConstants.WSSE_NS)) {
            return he;
        }
    }

    return null;
}