Example usage for javax.xml.soap MessageFactory newInstance

List of usage examples for javax.xml.soap MessageFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.soap MessageFactory newInstance.

Prototype

public static MessageFactory newInstance() throws SOAPException 

Source Link

Document

Creates a new MessageFactory object that is an instance of the default implementation (SOAP 1.1).

Usage

From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java

private String sendTQL(String query) {
    log.debug(query);//w  w w .  j ava 2s .c  o m
    String result = null;
    SOAPMessage reply = null;
    SOAPConnection connection = null;
    try {
        // Next, create the actual message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        message.getMimeHeaders().setHeader("SOAPAction", "itqlbean:executeQueryToString");
        SOAPBody soapBody = message.getSOAPPart().getEnvelope().getBody();
        soapBody.addNamespaceDeclaration("xsd", JDOMNamespaceUtil.XSD_NS.getURI());
        soapBody.addNamespaceDeclaration("xsi", JDOMNamespaceUtil.XSI_NS.getURI());
        soapBody.addNamespaceDeclaration("itqlbean", this.getItqlEndpointURL());
        SOAPElement eqts = soapBody.addChildElement("executeQueryToString", "itqlbean");
        SOAPElement queryStr = eqts.addChildElement("queryString", "itqlbean");
        queryStr.setAttributeNS(JDOMNamespaceUtil.XSI_NS.getURI(), "xsi:type", "xsd:string");
        CDATASection queryCDATA = message.getSOAPPart().createCDATASection(query);
        queryStr.appendChild(queryCDATA);
        message.saveChanges();

        // First create the connection
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
        connection = soapConnFactory.createConnection();
        reply = connection.call(message, this.getItqlEndpointURL());

        if (reply.getSOAPBody().hasFault()) {
            reportSOAPFault(reply);
            if (log.isDebugEnabled()) {
                // log the full soap body response
                DOMBuilder builder = new DOMBuilder();
                org.jdom2.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument());
                log.debug(new XMLOutputter().outputString(jdomDoc));
            }
        } else {
            NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*",
                    "executeQueryToStringReturn");
            if (nl.getLength() > 0) {
                result = nl.item(0).getFirstChild().getNodeValue();
            }
            log.debug(result);
        }
    } catch (SOAPException e) {
        log.error("Failed to prepare or send iTQL via SOAP", e);
        throw new RuntimeException("Cannot query triple store at " + this.getItqlEndpointURL(), e);
    } finally {
        try {
            connection.close();
        } catch (SOAPException e) {
            log.error("Failed to close SOAP connection", e);
            throw new RuntimeException(
                    "Failed to close SOAP connection for triple store at " + this.getItqlEndpointURL(), e);
        }
    }
    return result;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = Engine.theApp.schemaManager.makeResponse((Document) convertigoResponse);

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();//from  www  .  j  a  v a 2s .  co m

        addSoapElement(context, se, sb, document.getDocumentElement());

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

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 ww.ja  va 2s . c  om
 * @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:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private Document createSOAPFaultDocument(String faultString) throws SOAPException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart sp = message.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setPrefix(SOAP_PREFIX);/* ww w.j  av a  2s.com*/
    se.getHeader().detachNode();
    se.addHeader();
    se.getBody().detachNode();
    SOAPBody body = se.addBody();
    SOAPFault fault = body.addFault();
    Name faultCode = se.createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
    fault.setFaultCode(faultCode);
    fault.setFaultString(faultString);
    return se.getOwnerDocument();
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testSuccessfulEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();//from  ww  w . j  av  a2 s .c  o m

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));

    //printDocument(authnRequestMessage.getSOAPPart().getContent(), System.out);

    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "password";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "text/xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));

    //printDocument(responseMessage.getSOAPPart().getContent(), System.out);

    SOAPHeader responseMessageHeaders = responseMessage.getSOAPHeader();

    NodeList ecpResponse = responseMessageHeaders.getElementsByTagNameNS(
            JBossSAMLURIConstants.ECP_PROFILE.get(), JBossSAMLConstants.RESPONSE__ECP.get());

    Assert.assertThat("No ECP Response", ecpResponse.getLength(), is(1));

    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    ResponseType responseType = (ResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getValue().toString(), is(JBossSAMLURIConstants.STATUS_SUCCESS.get()));
    Assert.assertThat(responseType.getDestination(), is(ecpSPPage.toString() + "/"));
    Assert.assertThat(responseType.getSignature(), notNullValue());
    Assert.assertThat(responseType.getAssertions().size(), is(1));

    SOAPMessage samlResponseRequest = MessageFactory.newInstance().createMessage();

    samlResponseRequest.getSOAPBody().addDocument(responseMessage.getSOAPBody().extractContentAsDocument());

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    samlResponseRequest.writeTo(os);

    Response serviceProviderFinalResponse = ClientBuilder.newClient().target(responseType.getDestination())
            .request().post(Entity.entity(os.toByteArray(), "application/vnd.paos+xml"));

    Map<String, NewCookie> cookies = serviceProviderFinalResponse.getCookies();

    Invocation.Builder resourceRequest = ClientBuilder.newClient().target(responseType.getDestination())
            .request();

    for (NewCookie cookie : cookies.values()) {
        resourceRequest.cookie(cookie);
    }

    Response resourceResponse = resourceRequest.get();
    Assert.assertThat(resourceResponse.readEntity(String.class), containsString("pedroigor"));
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testInvalidCredentialsEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();/*  ww  w .  j  a  v  a2s .  c o  m*/

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader()
            .<SOAPHeaderElement>getChildElements(new QName("urn:liberty:paos:2003-08", "Request"));

    it.next();

    it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "baspassword";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "application/soap+xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    StatusResponseType responseType = (StatusResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getStatusCode().getValue().toString(),
            is(not(JBossSAMLURIConstants.STATUS_SUCCESS.get())));
}

From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java

/**
 * Create a MessageFactory singleton/*w w  w. j  a  v  a2 s.c  o  m*/
 * @return previously initialized or newly created MessageFactory
 */
private synchronized MessageFactory getMessageFactory() throws SOAPException {
    if (factory == null) {
        log.debug("creating new MessageFactory");
        factory = MessageFactory.newInstance();
    }

    return factory;
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//  w  w  w .  j  a va 2  s .  c o m
public void testStringAttachment() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    AttachmentPart attachment = message.createAttachmentPart();
    String stringContent = "Update address for Sunny Skies "
            + "Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439";

    attachment.setContent(stringContent, "text/plain");
    attachment.setContentId("update_address");
    message.addAttachmentPart(attachment);

    assertTrue(message.countAttachments() == 1);

    Iterator it = message.getAttachments();
    while (it.hasNext()) {
        attachment = (AttachmentPart) it.next();
        Object content = attachment.getContent();
        String id = attachment.getContentId();
        assertEquals(content, stringContent);
    }
    message.removeAllAttachments();
    assertTrue(message.countAttachments() == 0);
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//from  w  ww  . j a v a  2  s  . c  o m
public void testMultipleAttachments() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();

    AttachmentPart a1 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a1.setContentType("text/xml");
    msg.addAttachmentPart(a1);
    AttachmentPart a2 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a2.setContentType("text/xml");
    msg.addAttachmentPart(a2);
    AttachmentPart a3 = msg.createAttachmentPart(new DataHandler("text", "text/plain"));
    a3.setContentType("text/plain");
    msg.addAttachmentPart(a3);

    assertTrue(msg.countAttachments() == 3);

    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");

    int nAttachments = 0;
    Iterator iterator = msg.getAttachments(mimeHeaders);
    while (iterator.hasNext()) {
        nAttachments++;
        AttachmentPart ap = (AttachmentPart) iterator.next();
        assertTrue(ap.equals(a1) || ap.equals(a2));
    }
    assertTrue(nAttachments == 2);
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Test
public void testBadAttSize() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();

    ByteArrayInputStream ins = new ByteArrayInputStream(new byte[5]);
    DataHandler dh = new DataHandler(new Src(ins, "text/plain"));
    AttachmentPart part = message.createAttachmentPart(dh);
    assertEquals("Size should match", 5, part.getSize());
}