Search in sources :

Example 1 with MessageFactory

use of javax.xml.soap.MessageFactory in project jdk8u_jdk by JetBrains.

the class SaajEmptyNamespaceTest method createSoapMessage.

// Create SOAP message with empty body
private static SOAPMessage createSoapMessage() throws SOAPException, UnsupportedEncodingException {
    String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<SOAP-ENV:Body/></SOAP-ENV:Envelope>";
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage msg = mFactory.createMessage();
    msg.getSOAPPart().setContent(new StreamSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
    return msg;
}
Also used : MessageFactory(javax.xml.soap.MessageFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) StreamSource(javax.xml.transform.stream.StreamSource) SOAPMessage(javax.xml.soap.SOAPMessage)

Example 2 with MessageFactory

use of javax.xml.soap.MessageFactory in project openhab1-addons by openhab.

the class Tr064Comm method setTr064Value.

/***
     * Sets a parameter in fbox. Called from event bus
     *
     * @param request config string from itemconfig
     * @param cmd command to set
     */
public void setTr064Value(String request, Command cmd) {
    // extract itemCommand from request
    String[] itemConfig = request.split(":");
    // command is always first
    String itemCommand = itemConfig[0];
    // search for proper item Mapping
    ItemMap itemMap = determineItemMappingByItemCommand(itemCommand);
    // determine which url etc. to connect to for accessing required value
    Tr064Service tr064service = determineServiceByItemMapping(itemMap);
    // construct soap Body which is added to soap msg later
    // holds data to be sent to fbox
    SOAPBodyElement bodyData = null;
    try {
        MessageFactory mf = MessageFactory.newInstance();
        // empty message
        SOAPMessage msg = mf.createMessage();
        // std. SAOP body
        SOAPBody body = msg.getSOAPBody();
        // header
        QName bodyName = new QName(tr064service.getServiceType(), itemMap.getWriteServiceCommand(), "u");
        // for
        // body
        // element
        bodyData = body.addBodyElement(bodyName);
        // only if input parameter is present
        if (itemConfig.length > 1) {
            // additional parameter to set e.g. id of TAM to set
            String dataInValueAdd = itemConfig[1];
            // name of additional para to set
            QName dataNode = new QName(itemMap.getWriteDataInNameAdditional());
            SOAPElement beDataNode = bodyData.addChildElement(dataNode);
            // add value which should be set
            beDataNode.addTextNode(dataInValueAdd);
        }
        // convert String command into numeric
        String setDataInValue = cmd.toString().equalsIgnoreCase("on") ? "1" : "0";
        // service specific node name
        QName dataNode = new QName(itemMap.getWriteDataInName());
        SOAPElement beDataNode = bodyData.addChildElement(dataNode);
        // add data which should be requested from fbox for this service
        beDataNode.addTextNode(setDataInValue);
        logger.debug("SOAP Msg to send to FritzBox for setting data: {}", soapToString(msg));
    } catch (Exception e) {
        logger.error("Error constructing request SOAP msg for setting parameter. {}", e.getMessage());
        logger.debug("Request was: {}. Command was: {}.", request, cmd.toString());
    }
    if (bodyData == null) {
        logger.error("Could not determine data to be sent to FritzBox!");
        return;
    }
    // construct entire msg with body element
    SOAPMessage smTr064Request = constructTr064Msg(bodyData);
    // needed to
    String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getWriteServiceCommand();
    // be sent
    // with
    // request
    // (not in
    // body ->
    // header)
    SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request, _url + tr064service.getControlUrl());
    if (response == null) {
        logger.error("Error retrieving SOAP response from FritzBox");
        return;
    }
    logger.debug("SOAP response from FritzBox: {}", soapToString(response));
    // Check if error received
    try {
        if (response.getSOAPBody().getFault() != null) {
            logger.error("Error received from FritzBox while trying to set parameter");
            logger.debug("Soap Response was: {}", soapToString(response));
        }
    } catch (SOAPException e) {
        logger.error("Could not parse soap response from FritzBox while setting parameter. {}", e.getMessage());
        logger.debug("Soap Response was: {}", soapToString(response));
    }
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) MessageFactory(javax.xml.soap.MessageFactory) QName(javax.xml.namespace.QName) SOAPException(javax.xml.soap.SOAPException) SOAPElement(javax.xml.soap.SOAPElement) SOAPMessage(javax.xml.soap.SOAPMessage) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) SOAPBodyElement(javax.xml.soap.SOAPBodyElement)

Example 3 with MessageFactory

use of javax.xml.soap.MessageFactory in project openhab1-addons by openhab.

the class Tr064Comm method getTr064Value.

/***
     * Fetches a specific value from FritzBox
     *
     *
     * @param request string from config including the command and optional parameters
     * @return parsed value
     */
public String getTr064Value(String request) {
    String value = null;
    // extract itemCommand from request
    String[] itemConfig = request.split(":");
    // command is always first
    String itemCommand = itemConfig[0];
    // search for proper item Mapping
    ItemMap itemMap = determineItemMappingByItemCommand(itemCommand);
    if (itemMap == null) {
        logger.warn("No item mapping found for {}. Function not implemented by your FritzBox (?)", request);
        return "";
    }
    // determine which url etc. to connect to for accessing required value
    Tr064Service tr064service = determineServiceByItemMapping(itemMap);
    // construct soap Body which is added to soap msg later
    // holds data to be sent to fbox
    SOAPBodyElement bodyData = null;
    try {
        MessageFactory mf = MessageFactory.newInstance();
        // empty message
        SOAPMessage msg = mf.createMessage();
        // std. SAOP body
        SOAPBody body = msg.getSOAPBody();
        // header
        QName bodyName = new QName(tr064service.getServiceType(), itemMap.getReadServiceCommand(), "u");
        // for body
        // element
        bodyData = body.addBodyElement(bodyName);
        // only if input parameter is present
        if (itemConfig.length > 1) {
            String dataInValue = itemConfig[1];
            // service specific node name
            QName dataNode = new QName(itemMap.getReadDataInName());
            SOAPElement beDataNode = bodyData.addChildElement(dataNode);
            // if input is mac address, replace "-" with ":" as fbox wants
            if (itemMap.getItemCommand().equals("maconline")) {
                dataInValue = dataInValue.replaceAll("-", ":");
            }
            // add data which should be requested from fbox for this service
            beDataNode.addTextNode(dataInValue);
        }
        logger.trace("Raw SOAP Request to be sent to FritzBox: {}", soapToString(msg));
    } catch (Exception e) {
        logger.error("Error constructing request SOAP msg for getting parameter. {}", e.getMessage());
        logger.debug("Request was: {}", request);
    }
    if (bodyData == null) {
        logger.error("Could not determine data to be sent to FritzBox!");
        return null;
    }
    // construct entire msg with body element
    SOAPMessage smTr064Request = constructTr064Msg(bodyData);
    // needed to be
    String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getReadServiceCommand();
    // sent with
    // request (not
    // in body ->
    // header)
    SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request, _url + tr064service.getControlUrl());
    logger.trace("Raw SOAP Response from FritzBox: {}", soapToString(response));
    if (response == null) {
        logger.error("Error retrieving SOAP response from FritzBox");
        return null;
    }
    // check if special "soap value parser" handler for extracting SOAP value is defined. If yes, use svp
    if (itemMap.getSoapValueParser() == null) {
        // extract dataOutName1 as default, no handler used
        NodeList nlDataOutNodes = response.getSOAPPart().getElementsByTagName(itemMap.getReadDataOutName());
        if (nlDataOutNodes != null && nlDataOutNodes.getLength() > 0) {
            // extract value from soap response
            value = nlDataOutNodes.item(0).getTextContent();
        } else {
            logger.error("FritzBox returned unexpected response. Could not find expected datavalue {} in response.", itemMap.getReadDataOutName());
            logger.debug(soapToString(response));
        }
    } else {
        logger.debug("Parsing response using SOAP value parser in Item map");
        // itemMap is
        value = itemMap.getSoapValueParser().parseValueFromSoapMessage(response, itemMap, request);
    // passed for
    // accessing
    // mapping in
    // anonymous
    // method
    // (better way
    // to do??)
    }
    return value;
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) MessageFactory(javax.xml.soap.MessageFactory) QName(javax.xml.namespace.QName) NodeList(org.w3c.dom.NodeList) SOAPElement(javax.xml.soap.SOAPElement) SOAPMessage(javax.xml.soap.SOAPMessage) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) SOAPBodyElement(javax.xml.soap.SOAPBodyElement)

Example 4 with MessageFactory

use of javax.xml.soap.MessageFactory in project keycloak by keycloak.

the class EcpAuthenticationHandler method createChallenge.

@Override
protected AbstractInitiateLogin createChallenge() {
    return new AbstractInitiateLogin(deployment, sessionStore) {

        @Override
        protected void sendAuthnRequest(HttpFacade httpFacade, SAML2AuthnRequestBuilder authnRequestBuilder, BaseSAML2BindingBuilder binding) {
            try {
                MessageFactory messageFactory = MessageFactory.newInstance();
                SOAPMessage message = messageFactory.createMessage();
                SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
                envelope.addNamespaceDeclaration(NS_PREFIX_SAML_ASSERTION, JBossSAMLURIConstants.ASSERTION_NSURI.get());
                envelope.addNamespaceDeclaration(NS_PREFIX_SAML_PROTOCOL, JBossSAMLURIConstants.PROTOCOL_NSURI.get());
                envelope.addNamespaceDeclaration(NS_PREFIX_PAOS_BINDING, JBossSAMLURIConstants.PAOS_BINDING.get());
                envelope.addNamespaceDeclaration(NS_PREFIX_PROFILE_ECP, JBossSAMLURIConstants.ECP_PROFILE.get());
                createPaosRequestHeader(envelope);
                createEcpRequestHeader(envelope);
                SOAPBody body = envelope.getBody();
                body.addDocument(binding.postBinding(authnRequestBuilder.toDocument()).getDocument());
                message.writeTo(httpFacade.getResponse().getOutputStream());
            } catch (Exception e) {
                throw new RuntimeException("Could not create AuthnRequest.", e);
            }
        }

        private void createEcpRequestHeader(SOAPEnvelope envelope) throws SOAPException {
            SOAPHeader headers = envelope.getHeader();
            SOAPHeaderElement ecpRequestHeader = headers.addHeaderElement(envelope.createQName(JBossSAMLConstants.REQUEST.get(), NS_PREFIX_PROFILE_ECP));
            ecpRequestHeader.setMustUnderstand(true);
            ecpRequestHeader.setActor("http://schemas.xmlsoap.org/soap/actor/next");
            ecpRequestHeader.addAttribute(envelope.createName("ProviderName"), deployment.getEntityID());
            ecpRequestHeader.addAttribute(envelope.createName("IsPassive"), "0");
            ecpRequestHeader.addChildElement(envelope.createQName("Issuer", "saml")).setValue(deployment.getEntityID());
            ecpRequestHeader.addChildElement(envelope.createQName("IDPList", "samlp")).addChildElement(envelope.createQName("IDPEntry", "samlp")).addAttribute(envelope.createName("ProviderID"), deployment.getIDP().getEntityID()).addAttribute(envelope.createName("Name"), deployment.getIDP().getEntityID()).addAttribute(envelope.createName("Loc"), deployment.getIDP().getSingleSignOnService().getRequestBindingUrl());
        }

        private void createPaosRequestHeader(SOAPEnvelope envelope) throws SOAPException {
            SOAPHeader headers = envelope.getHeader();
            SOAPHeaderElement paosRequestHeader = headers.addHeaderElement(envelope.createQName(JBossSAMLConstants.REQUEST.get(), NS_PREFIX_PAOS_BINDING));
            paosRequestHeader.setMustUnderstand(true);
            paosRequestHeader.setActor("http://schemas.xmlsoap.org/soap/actor/next");
            paosRequestHeader.addAttribute(envelope.createName("service"), JBossSAMLURIConstants.ECP_PROFILE.get());
            paosRequestHeader.addAttribute(envelope.createName("responseConsumerURL"), getResponseConsumerUrl());
        }

        private String getResponseConsumerUrl() {
            return (deployment.getIDP() == null || deployment.getIDP().getSingleSignOnService() == null || deployment.getIDP().getSingleSignOnService().getAssertionConsumerServiceUrl() == null) ? null : deployment.getIDP().getSingleSignOnService().getAssertionConsumerServiceUrl().toString();
        }
    };
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) SOAPBody(javax.xml.soap.SOAPBody) MessageFactory(javax.xml.soap.MessageFactory) AbstractInitiateLogin(org.keycloak.adapters.saml.AbstractInitiateLogin) HttpFacade(org.keycloak.adapters.spi.HttpFacade) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SAML2AuthnRequestBuilder(org.keycloak.saml.SAML2AuthnRequestBuilder) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 5 with MessageFactory

use of javax.xml.soap.MessageFactory in project keycloak by keycloak.

the class EcpAuthenticationHandler method handle.

@Override
public AuthOutcome handle(OnSessionCreated onCreateSession) {
    String header = facade.getRequest().getHeader(PAOS_HEADER);
    if (header != null) {
        return doHandle(new SamlInvocationContext(), onCreateSession);
    } else {
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage soapMessage = messageFactory.createMessage(null, facade.getRequest().getInputStream());
            SOAPBody soapBody = soapMessage.getSOAPBody();
            Node authnRequestNode = soapBody.getFirstChild();
            Document document = DocumentUtil.createDocument();
            document.appendChild(document.importNode(authnRequestNode, true));
            String samlResponse = PostBindingUtil.base64Encode(DocumentUtil.asString(document));
            return doHandle(new SamlInvocationContext(null, samlResponse, null), onCreateSession);
        } catch (Exception e) {
            throw new RuntimeException("Error creating fault message.", e);
        }
    }
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) MessageFactory(javax.xml.soap.MessageFactory) SamlInvocationContext(org.keycloak.adapters.saml.profile.SamlInvocationContext) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException)

Aggregations

MessageFactory (javax.xml.soap.MessageFactory)70 SOAPMessage (javax.xml.soap.SOAPMessage)65 URL (java.net.URL)24 InputStream (java.io.InputStream)22 QName (javax.xml.namespace.QName)22 SOAPException (javax.xml.soap.SOAPException)22 Test (org.junit.Test)21 ByteArrayInputStream (java.io.ByteArrayInputStream)19 SOAPBody (javax.xml.soap.SOAPBody)18 SOAPPart (javax.xml.soap.SOAPPart)17 StreamSource (javax.xml.transform.stream.StreamSource)14 SOAPConnection (javax.xml.soap.SOAPConnection)13 IOException (java.io.IOException)11 SOAPElement (javax.xml.soap.SOAPElement)11 RunAsClient (org.jboss.arquillian.container.test.api.RunAsClient)10 JBossWSTest (org.jboss.wsf.test.JBossWSTest)10 NodeList (org.w3c.dom.NodeList)9 AttachmentPart (javax.xml.soap.AttachmentPart)8 SOAPEnvelope (javax.xml.soap.SOAPEnvelope)8 Element (org.w3c.dom.Element)8