Example usage for javax.xml.soap SOAPMessage getSOAPHeader

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

Introduction

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

Prototype

public SOAPHeader getSOAPHeader() throws SOAPException 

Source Link

Document

Gets the SOAP Header contained in this SOAPMessage object.

Usage

From source file:be.e_contract.dssp.client.WSSecuritySOAPHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    if (null == this.session && null == this.username) {
        return;/*from w w  w.  jav  a2s  .  c  om*/
    }
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPHeader soapHeader;
    try {
        soapHeader = soapMessage.getSOAPHeader();
    } catch (SOAPException e) {
        // WebSphere 8.5.5.1 work-around.
        soapHeader = null;
    }
    if (null == soapHeader) {
        /*
         * Work-around for Axis2.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement = wsSecHeader.insertSecurityHeader(soapPart);

    if (null != this.session) {
        securityElement.appendChild(
                securityElement.getOwnerDocument().importNode(this.session.getSecurityTokenElement(), true));
    }

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.setTimeToLive(60);
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    if (null != this.username) {
        WSSecUsernameToken usernameToken = new WSSecUsernameToken();
        usernameToken.setUserInfo(this.username, this.password);
        usernameToken.setPasswordType(WSConstants.PASSWORD_TEXT);
        usernameToken.prepare(soapPart);
        usernameToken.prependToHeader(wsSecHeader);
    }

    if (null != this.session) {
        // work-around for WebSphere
        WSSConfig wssConfig = new WSSConfig();
        wssConfig.setWsiBSPCompliant(false);

        WSSecSignature wsSecSignature = new WSSecSignature(wssConfig);
        wsSecSignature.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
        wsSecSignature.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        wsSecSignature.setCustomTokenId(this.session.getSecurityTokenElement().getAttributeNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id"));
        wsSecSignature.setSecretKey(this.session.getKey());
        wsSecSignature.prepare(soapPart, null, wsSecHeader);
        Vector<WSEncryptionPart> signParts = new Vector<WSEncryptionPart>();
        SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(soapPart.getDocumentElement());
        signParts.add(new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content"));
        signParts.add(new WSEncryptionPart(wsSecTimeStamp.getId()));
        List<Reference> referenceList = wsSecSignature.addReferencesToSign(signParts, wsSecHeader);
        wsSecSignature.computeSignature(referenceList, false, null);
    }

    /*
     * Really needs to be at the end for Axis2 to work. Axiom bug?
     */
    appendSecurityHeader(soapHeader, securityElement);
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

@SuppressWarnings("unchecked")
private XRoadProtocolVersion parseProtocolVersion(SOAPMessage requestMessage) throws SOAPException {
    XRoadProtocolVersion version = null;
    // Extract protocol version by headers
    if (requestMessage.getSOAPHeader() != null) {
        NodeList reqHeaders = requestMessage.getSOAPHeader().getChildNodes();
        for (int i = 0; i < reqHeaders.getLength(); i++) {
            Node reqHeader = reqHeaders.item(i);
            if (reqHeader.getNodeType() != Node.ELEMENT_NODE
                    || !reqHeader.getLocalName().equals(XTeeHeader.PROTOCOL_VERSION.getLocalPart())) {
                continue;
            }//from  w  ww  . ja va 2 s .  co m

            if ((version = XRoadProtocolVersion
                    .getValueByVersionCode(SOAPUtil.getTextContent(reqHeader))) != null) {
                return version;
            }
        }
    }

    // Extract protocol version by namespaces
    SOAPEnvelope soapEnv = requestMessage.getSOAPPart().getEnvelope();
    Iterator<String> prefixes = soapEnv.getNamespacePrefixes();
    while (prefixes.hasNext()) {
        String nsPrefix = (String) prefixes.next();
        String nsURI = soapEnv.getNamespaceURI(nsPrefix).toLowerCase();
        if ((version = XRoadProtocolVersion.getValueByNamespaceURI(nsURI)) != null) {
            return version;
        }
    }
    throw new IllegalStateException("Unsupported protocol version");
}

From source file:eu.domibus.ebms3.receiver.MSHWebservice.java

private Messaging getMessaging(SOAPMessage request) throws SOAPException, JAXBException {
    Node messagingXml = (Node) request.getSOAPHeader().getChildElements(ObjectFactory._Messaging_QNAME).next();
    Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller(); //Those are not thread-safe, therefore a new one is created each call
    @SuppressWarnings("unchecked")
    JAXBElement<Messaging> root = (JAXBElement<Messaging>) unmarshaller.unmarshal(messagingXml);
    return root.getValue();
}

From source file:ee.ria.xroad.common.message.SoapParserImpl.java

protected Soap createMessage(byte[] rawXml, SOAPMessage soap, String charset, String originalContentType)
        throws Exception {
    // Request and response messages must have a header,
    // fault messages may or may not have a header.
    SoapHeader header = null;//from w  w w  .j a v  a  2  s.co  m
    if (soap.getSOAPHeader() != null) {
        validateSOAPHeader(soap.getSOAPHeader());
        header = unmarshalHeader(SoapHeader.class, soap.getSOAPHeader());
    }

    return createMessage(rawXml, header, soap, charset, originalContentType);
}

From source file:be.agiv.security.handler.WSSecurityHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException,
        ConversationException, SOAPException, IOException, XMLSignatureException, XMLSecurityException {
    LOG.debug("adding WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    if (null == soapHeader) {
        /*//from  www . j av a2  s  .  c om
         * Work-around for Axis2.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement = wsSecHeader.insertSecurityHeader(soapPart);

    addToken(context, securityElement);

    addUsernamePassword(context, soapPart, wsSecHeader);

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    addProofOfPossessionSignature(context, soapMessage, soapPart, wsSecHeader, wsSecTimeStamp);

    addCertificateSignature(context, soapPart, wsSecHeader, wsSecTimeStamp);

    /*
     * Really needs to be at the end for Axis2 to work. Axiom bug?
     */
    appendSecurityHeader(soapHeader, securityElement);
}

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

private SOAPMessage createSoapMessage(GetChargingPlans value) throws PEPException {
    try {/*w w  w . j a va2s  .c o m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(GetChargingPlans.class);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        jaxbContext.createMarshaller().marshal(value, document);

        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        soapMessage.getSOAPBody().addDocument(document);
        Name headername = soapMessage.getSOAPPart().getEnvelope().createName("Action", "",
                "http://schemas.microsoft.com/ws/2005/05/addressing/none/");
        SOAPHeaderElement soapAction = soapMessage.getSOAPHeader().addHeaderElement(headername);
        soapAction.setMustUnderstand(true);
        soapAction.setTextContent("http://tempuri.org/ISmartCharging/GetChargingPlans");
        return soapMessage;
    } catch (DOMException | JAXBException | ParserConfigurationException | SOAPException ex) {
        throw new PEPException(ex);
    }
}

From source file:com.hiperium.integration.access.control.SoapSignatureHandler.java

@SuppressWarnings("unchecked")
@Override//from www.  jav  a2 s.  c  o m
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        for (String session : this.getHTTPHeader(map, CommonsUtil.SESSIONID)) {
            sessionIdBuffer.append(session);
        }
        // Try to get SOAP header values from the SOAP message
        try {
            SOAPMessage msg = context.getMessage();
            if (LOGGER.isDebugEnabled()) {
                System.out.println("REQUEST:");
                msg.writeTo(System.out);
                System.out.println();
            }
            Node node = msg.getSOAPHeader().getFirstChild();

            // Header values
            NodeList nodeList = node.getChildNodes(); // Name, TimeStamp, Signature.
            if (nodeList.getLength() < 3) {
                this.generateFault(msg, "Too few header nodes!");
            }

            // Extract the required attributes.
            Long homeId = Long.valueOf(nodeList.item(0).getFirstChild().getNodeValue());
            String signature = nodeList.item(1).getFirstChild().getNodeValue();
            String timestamp = nodeList.item(2).getFirstChild().getNodeValue();
            if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) {
                this.generateFault(msg, "Missing header key/value pairs!");
            }

            // Validates that the user Token exists in the DB for valid registered external Application.
            String token = this.securityBusinessDelegate.getHomeGatewayBO().findTokenInSession(homeId,
                    sessionIdBuffer.toString());
            if (StringUtils.isBlank(token)) {
                this.generateFault(msg, homeId.toString().concat(" not registered!"));
            }

            // Generate comparison signature and compare against what's sent.
            byte[] secretBytes = Signature.getBytes(token);
            String localSignature = Signature.createSignature(homeId, timestamp, secretBytes);
            if (!this.verify(signature, localSignature)) {
                this.generateFault(msg, "HMAC signatures do not match.");
            }
        } catch (Exception e) {
            throw new RuntimeException("SOAPException thrown.", e);
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

public final void invoke(MessageContext messageContext) throws Exception {
    SOAPMessage paringMessage = SOAPUtil.extractSoapMessage(messageContext.getRequest());
    SOAPMessage responseMessage = SOAPUtil.extractSoapMessage(messageContext.getResponse());

    version = parseProtocolVersion(paringMessage);

    // meta-service does not need 'header' element
    if (metaService) {
        responseMessage.getSOAPHeader().detachNode();
    }/* w ww  . j av  a2s.c  o m*/

    Document paring = metaService ? null : parseQuery(paringMessage);
    getResponse(paring, responseMessage, paringMessage);
}

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

protected Map<String, String> addSoapMetaInfo(Map<String, String> metaInfo, SOAPMessage soapMessage)
        throws SOAPException {
    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    if (soapHeader == null) {
        return metaInfo;
    } else {//from  w  w  w .  j  ava2 s .c  o  m
        Map<String, String> newMetaInfo = new HashMap<String, String>();
        newMetaInfo.putAll(metaInfo);
        Iterator<?> iter = soapHeader.examineAllHeaderElements();
        while (iter.hasNext()) {
            SOAPHeaderElement headerElem = (SOAPHeaderElement) iter.next();
            if (!Listener.AUTHENTICATED_USER_HEADER.equals(headerElem.getNodeName()))
                newMetaInfo.put(headerElem.getNodeName(), headerElem.getTextContent());
        }
        return newMetaInfo;
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.ProxyMonitorServiceHandlerTest.java

@Test
public void startHandingShouldProduceAllMetrics() throws Exception {

    // setup//from   ww  w.  ja v  a  2s  . c o  m
    ProxyMonitorServiceHandlerImpl handlerToTest = new ProxyMonitorServiceHandlerImpl();

    final SoapMessageImpl soapMessage = build(DEFAULT_OWNER_CLIENT, MONITOR_SERVICE_ID, "testUser",
            randomUUID().toString());

    when(mockProxyMessage.getSoap()).thenReturn(soapMessage);
    when(mockProxyMessage.getSoapContent())
            .thenReturn(new ByteArrayInputStream(soapMessage.getXml().getBytes(soapMessage.getCharset())));

    handlerToTest.canHandle(MONITOR_SERVICE_ID, mockProxyMessage);

    final String expectedMetricsSetName = "someName";

    MetricSetType metricSetType = new MetricSetType();
    metricSetType.setName(expectedMetricsSetName);

    final List<MetricType> metrics = metricSetType.getMetrics();

    StringMetricType type = new StringMetricType();
    final String expectedMetricName = "metricName123-23";
    type.setName(expectedMetricName);

    final String expectedMetricValue = "123SomeValue";
    type.setValue(expectedMetricValue);
    metrics.add(type);

    MonitorClient mockMonitorClient = PowerMockito.mock(MonitorClient.class);
    PowerMockito.when(mockMonitorClient.getMetrics(anyList())).thenReturn(metricSetType);

    RestoreMonitorClientAfterTest.setMonitorClient(mockMonitorClient);

    // execution
    handlerToTest.startHandling(mockRequest, mockProxyMessage, mock(HttpClient.class),
            mock(OpMonitoringData.class));

    //verification
    assertThat("Wrong content type", handlerToTest.getResponseContentType(), is(TEXT_XML_UTF8));

    final SOAPMessage message = messageFactory.createMessage(null, handlerToTest.getResponseContent());

    final SoapHeader xrHeader = unmarshaller.unmarshal(message.getSOAPHeader(), SoapHeader.class).getValue();

    assertThat("Response client does not match", xrHeader.getClient(), is(DEFAULT_OWNER_CLIENT));
    assertThat("Response client does not match", xrHeader.getService(), is(MONITOR_SERVICE_ID));

    final MetricSetType root = verifyAndGetSingleBodyElementOfType(message.getSOAPBody(),
            GetSecurityServerMetricsResponse.class, () -> unmarshaller).getMetricSet();
    // root metrics should have the security server id as name
    assertThat("Metrics set name does not match", root.getName(), is(DEFAULT_OWNER_SERVER.toString()));

    final List<MetricType> responseMetrics = root.getMetrics();
    assertThat("Missing proxy version from metrics", responseMetrics,
            hasItem(hasProperty("name", is("proxyVersion"))));

    assertThat("Missing the expected metrics set", responseMetrics, hasItem(instanceOf(MetricSetType.class)));

    final MetricSetType responseDataMetrics = (MetricSetType) responseMetrics.stream() // we just asserted this..
            .filter(m -> m instanceof MetricSetType).findFirst().orElseThrow(IllegalStateException::new);

    assertThat(responseDataMetrics.getName(), is(expectedMetricsSetName));
    assertThat(responseDataMetrics.getMetrics().size(), is(1));

    final StringMetricType responseMetric = (StringMetricType) responseDataMetrics.getMetrics().get(0);
    assertThat("Wrong metric name", responseMetric.getName(), is(expectedMetricName));
    assertThat("Wrong metric value", responseMetric.getValue(), is(expectedMetricValue));
}