Example usage for javax.xml.soap SOAPConnectionFactory createConnection

List of usage examples for javax.xml.soap SOAPConnectionFactory createConnection

Introduction

In this page you can find the example usage for javax.xml.soap SOAPConnectionFactory createConnection.

Prototype

public abstract SOAPConnection createConnection() throws SOAPException;

Source Link

Document

Create a new SOAPConnection .

Usage

From source file:org.overlord.rtgov.tests.platforms.jbossas.slamonitor.JBossASSLAMonitorTest.java

@Test
@OperateOnDeployment("orders-app")
@Ignore//from   www  .  java2s.  c  o m
public void testResponseTimesOnFaultFromACMgr() {

    try {
        SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = factory.createConnection();

        java.net.URL url = new java.net.URL(ORDER_SERVICE_URL);

        String mesg = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "   <soap:Body>"
                + "       <orders:submitOrder xmlns:orders=\"urn:switchyard-quickstart-demo:orders:1.0\">"
                + "            <order>" + "                <orderId>PO-19838-XYZ</orderId>"
                + "                <itemId>LAPTOP</itemId>" + "                <quantity>200</quantity>"
                + "                <customer>Fred</customer>" + "            </order>"
                + "        </orders:submitOrder>" + "    </soap:Body>" + "</soap:Envelope>";

        java.io.InputStream is = new java.io.ByteArrayInputStream(mesg.getBytes());

        SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);

        is.close();

        // Preload results
        QuerySpec qs1 = new QuerySpec();
        qs1.setCollection(SERVICE_RESPONSE_TIMES);

        java.util.List<?> result1base = performACMQuery(qs1);

        SOAPMessage response = con.call(request, url);

        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

        response.writeTo(baos);

        String resp = baos.toString();

        baos.close();

        if (!resp.contains("Item Not Available")) {
            fail("Item not available response not received");
        }

        // Wait for events to propagate
        Thread.sleep(4000);

        java.util.List<?> result1 = performACMQuery(qs1);

        System.out.println("RETRIEVED RESULTS (Fault)=" + result1);

        if (result1 == null) {
            fail("Result 1 is null");
        }

        if (result1.size() - result1base.size() != 2) {
            fail("2 events expected, but got: " + result1.size() + " - " + result1base.size() + " = "
                    + (result1.size() - result1base.size()));
        }

    } catch (Exception e) {
        fail("Failed to invoke service: " + e);
    }
}

From source file:org.overlord.rtgov.tests.platforms.jbossas.slamonitor.JBossASSLAMonitorTest.java

@Test
@OperateOnDeployment("orders-app")
public void testActivityEventsProcessed() {

    EPNManager epnManager = EPNManagerAccessor.getEPNManager();

    TestListener tl = new TestListener();

    epnManager.addNotificationListener(SITUATIONS_PROCESSED, tl);

    try {//from   ww w.java2  s. c  o m
        SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = factory.createConnection();

        java.net.URL url = new java.net.URL(ORDER_SERVICE_URL);

        String mesg = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "   <soap:Body>"
                + "       <orders:submitOrder xmlns:orders=\"urn:switchyard-quickstart-demo:orders:1.0\">"
                + "            <order>" + "                <orderId>PO-19838-XYZ</orderId>"
                + "                <itemId>BUTTER</itemId>" + "                <quantity>200</quantity>"
                + "                <customer>Fred</customer>" + "            </order>"
                + "        </orders:submitOrder>" + "    </soap:Body>" + "</soap:Envelope>";

        java.io.InputStream is = new java.io.ByteArrayInputStream(mesg.getBytes());

        SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);

        is.close();

        SOAPMessage response = con.call(request, url);

        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

        response.writeTo(baos);

        String resp = baos.toString();

        baos.close();

        if (!resp.contains("<accepted>true</accepted>")) {
            fail("Order was not accepted: " + resp);
        }

        // Wait for events to propagate
        Thread.sleep(4000);

        if (tl.getEvents(SITUATIONS_PROCESSED) == null) {
            fail("Expecting situations processed");
        }

        // 6 instead of 3 due to the introduction of the second EPN node that also checks for SLA
        // violations, but does not generate any new situations - but this notification channel is
        // for events before they are processed.
        if (tl.getEvents(SITUATIONS_PROCESSED).size() != 6) {
            fail("Expecting 6 (sla situations) processed events, but got: "
                    + tl.getEvents(SITUATIONS_PROCESSED).size());
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail("Failed to invoke service via SOAP: " + e);
    } finally {
        epnManager.removeNotificationListener(SITUATIONS_PROCESSED, tl);
    }
}

From source file:org.overlord.rtgov.tests.platforms.jbossas.slamonitor.JBossASSLAMonitorTest.java

@Test
@OperateOnDeployment("orders-app")
public void testActivityEventsResults() {

    EPNManager epnManager = EPNManagerAccessor.getEPNManager();

    TestListener tl = new TestListener();

    epnManager.addNotificationListener(SITUATIONS, tl);

    try {/*from  w  w w.j  av a  2  s  .  com*/
        SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = factory.createConnection();

        java.net.URL url = new java.net.URL(ORDER_SERVICE_URL);

        String mesg = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "   <soap:Body>"
                + "       <orders:submitOrder xmlns:orders=\"urn:switchyard-quickstart-demo:orders:1.0\">"
                + "            <order>" + "                <orderId>PO-13739-ABC</orderId>"
                + "                <itemId>JAM</itemId>" + "                <quantity>50</quantity>"
                + "                <customer>Fred</customer>" + "            </order>"
                + "        </orders:submitOrder>" + "    </soap:Body>" + "</soap:Envelope>";

        java.io.InputStream is = new java.io.ByteArrayInputStream(mesg.getBytes());

        SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);

        is.close();

        SOAPMessage response = con.call(request, url);

        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

        response.writeTo(baos);

        String resp = baos.toString();

        baos.close();

        if (!resp.contains("<accepted>true</accepted>")) {
            fail("Order was not accepted: " + resp);
        }

        // Wait for events to propagate
        Thread.sleep(2000);

        // Check that all events have been processed
        if (tl.getEvents(SITUATIONS) == null) {
            fail("Expecting sla violations results");
        }

        if (tl.getEvents(SITUATIONS).size() != 2) {
            fail("Expecting 2 (sla violations) results events, but got: " + tl.getEvents(SITUATIONS).size());
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail("Failed to invoke service via SOAP: " + e);
    } finally {
        epnManager.removeNotificationListener(SITUATIONS, tl);
    }
}

From source file:org.sakaiproject.compilatio.util.CompilatioAPIUtil.java

public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters,
        String secretKey, final int timeout) throws TransientSubmissionException, SubmissionException {

    SOAPConnectionFactory soapConnectionFactory;
    Document xmlDocument = null;//ww  w  . j  a v  a 2  s.  co m
    try {
        soapConnectionFactory = SOAPConnectionFactory.newInstance();

        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
        parameters.remove("action");
        // api key
        SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
        soapBodyKey.addTextNode(secretKey);

        Set<Entry<String, String>> ets = parameters.entrySet();
        Iterator<Entry<String, String>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, String> param = it.next();
            SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
            soapBodyElement.addTextNode(param.getValue());
        }

        URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                URL target = new URL(url.toString());
                URLConnection connection = target.openConnection();
                // Connection settings
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                return (connection);
            }
        });

        SOAPMessage soapResponse = soapConnection.call(soapMessage, endpoint);

        // loading the XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
        soapConnection.close();

    } catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException
            | SAXException e) {
        log.error(e);
    }
    return xmlDocument;

}

From source file:org.sakaiproject.contentreview.compilatio.util.CompilatioAPIUtil.java

public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters,
        String secretKey, final int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {

    SOAPConnectionFactory soapConnectionFactory;
    Document xmlDocument = null;/*from   ww  w  .j  a va 2  s . co m*/
    try {
        soapConnectionFactory = SOAPConnectionFactory.newInstance();

        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
        parameters.remove("action");
        // api key
        SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
        soapBodyKey.addTextNode(secretKey);

        Set<Entry<String, String>> ets = parameters.entrySet();
        Iterator<Entry<String, String>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, String> param = it.next();
            SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
            soapBodyElement.addTextNode(param.getValue());
        }

        URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                URL target = new URL(url.toString());
                URLConnection connection = target.openConnection();
                // Connection settings
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                return (connection);
            }
        });

        SOAPMessage soapResponse = soapConnection.call(soapMessage, endpoint);

        // loading the XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
        soapConnection.close();

    } catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException
            | SAXException e) {
        log.error(e);
    }
    return xmlDocument;

}

From source file:org.wso2.carbon.identity.provisioning.connector.InweboUserManager.java

/**
 * Method to create SOAP connection//from   w  w  w.  j a  v a  2s . co  m
 */
public static String invokeSOAP(InweboUser user, String operation) throws IdentityProvisioningException {
    String provisionedId = null;
    SOAPConnectionFactory soapConnectionFactory = null;
    SOAPConnection soapConnection = null;
    try {
        Properties inweboProperties = new Properties();
        String resourceName = InweboConnectorConstants.PROPERTIES_FILE;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream resourceStream = loader.getResourceAsStream(resourceName);
        try {
            inweboProperties.load(resourceStream);
        } catch (IOException e) {
            throw new IdentityProvisioningException("Unable to load the properties file", e);
        }

        SOAPMessage soapMessage = null;
        soapConnectionFactory = SOAPConnectionFactory.newInstance();
        soapConnection = soapConnectionFactory.createConnection();
        String url = inweboProperties.getProperty(InweboConnectorConstants.INWEBO_URL);
        if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_POST)) {
            soapMessage = createUserSOAPMessage(inweboProperties, user);
        } else if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_PUT)) {
            soapMessage = updateUserSOAPMessage(inweboProperties, user);
        } else if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_DELETE)) {
            soapMessage = deleteUserSOAPMessage(inweboProperties, user.getLoginId(), user.getUserId(),
                    user.getServiceId());
        }
        SOAPMessage soapResponse = soapConnection.call(soapMessage, url);
        if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_POST)) {
            if (soapResponse.getSOAPBody().getElementsByTagName("id").getLength() != 0) {
                provisionedId = soapResponse.getSOAPBody().getElementsByTagName("id").item(0).getTextContent()
                        .toString();
                if (StringUtils.isEmpty(provisionedId) || "0".equals(provisionedId)) {
                    String error = soapResponse.getSOAPBody().getElementsByTagName("loginCreateReturn").item(0)
                            .getTextContent().toString();
                    throw new IdentityProvisioningException(
                            "Error occurred while creating the user in InWebo:" + error);
                }
            } else {
                throw new IdentityProvisioningException("Unable to find the provisioning ID");
            }
        } else if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_PUT)) {
            if (soapResponse.getSOAPBody().getElementsByTagName("loginUpdateReturn").getLength() != 0) {
                String updationStatus = soapResponse.getSOAPBody().getElementsByTagName("loginUpdateReturn")
                        .item(0).getTextContent().toString();
                boolean processStatus = StringUtils.equals("OK", updationStatus);
                if (!processStatus) {
                    String error = soapResponse.getSOAPBody().getElementsByTagName("loginUpdateReturn").item(0)
                            .getTextContent().toString();
                    throw new IdentityProvisioningException(
                            "Error occurred while updating the user in InWebo:" + error);
                }
            } else {
                throw new IdentityProvisioningException("Unable to get the updation status");
            }
        } else if (operation.equals(InweboConnectorConstants.INWEBO_OPERATION_DELETE)) {
            if (soapResponse.getSOAPBody().getElementsByTagName("loginDeleteReturn").getLength() != 0) {
                String deletionStatus = soapResponse.getSOAPBody().getElementsByTagName("loginDeleteReturn")
                        .item(0).getTextContent().toString();
                boolean processStatus = StringUtils.equals("OK", deletionStatus);
                if (!processStatus) {
                    String error = soapResponse.getSOAPBody().getElementsByTagName("loginDeleteReturn").item(0)
                            .getTextContent().toString();
                    throw new IdentityProvisioningException(
                            "Error occurred while deleting the user from InWebo:" + error);
                }
            } else {
                throw new IdentityProvisioningException("Unable to get the operation status");
            }
        }
    } catch (SOAPException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    } finally {
        try {
            if (soapConnection != null) {
                soapConnection.close();
            }
        } catch (SOAPException e) {
            log.error("Error while closing the SOAP connection", e);
        }
    }
    return provisionedId;
}

From source file:org.wso2.carbon.identity.provisioning.connector.UserCreation.java

/**
 * Method for create SOAP connection/*w w  w .  j  av a 2s. c o m*/
 */
public static String invokeSOAP(String userId, String serviceId, String login, String firstName, String name,
        String mail, String phone, String status, String role, String access, String codeType, String language,
        String extraFields) throws IdentityProvisioningException {
    String provisionedId = null;
    try {
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        String url = InweboConnectorConstants.INWEBO_URL;
        SOAPMessage soapResponse = soapConnection.call(createUser(userId, serviceId, login, firstName, name,
                mail, phone, status, role, access, codeType, language, extraFields), url);
        provisionedId = soapResponse.getSOAPBody().getElementsByTagName("id").item(0).getTextContent()
                .toString();
        soapConnection.close();
        if (StringUtils.isEmpty(provisionedId) || provisionedId.equals("0")) {
            String error = soapResponse.getSOAPBody().getElementsByTagName("loginCreateReturn").item(0)
                    .getTextContent().toString();
            throw new IdentityProvisioningException(
                    "Error occurred while creating the user in InWebo:" + error);
        }
    } catch (SOAPException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    } catch (IdentityProvisioningException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    }
    return provisionedId;
}

From source file:org.wso2.carbon.identity.provisioning.connector.UserDeletion.java

public boolean deleteUser(String loginId, String userId, String serviceId)
        throws IdentityProvisioningException {
    try {//from  ww w. j  av a  2  s .c om
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        String url = InweboConnectorConstants.INWEBO_URL;
        SOAPMessage soapResponse = soapConnection.call(deleteUsers(loginId, userId, serviceId), url);
        String deletionStatus = soapResponse.getSOAPBody().getElementsByTagName("loginDeleteReturn").item(0)
                .getTextContent().toString();
        soapConnection.close();
        boolean processStatus = StringUtils.equals("OK", deletionStatus);
        if (!processStatus) {
            String error = soapResponse.getSOAPBody().getElementsByTagName("loginDeleteReturn").item(0)
                    .getTextContent().toString();
            throw new IdentityProvisioningException(
                    "Error occurred while deleting the user from InWebo:" + error);
        }
        return processStatus;
    } catch (SOAPException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    } catch (IdentityProvisioningException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    }
}

From source file:org.wso2.carbon.identity.provisioning.connector.UserUpdation.java

/**
 * Method for create SOAP connection//from  www  . j av a  2  s . co  m
 */
public static boolean invokeSOAP(String userId, String serviceId, String loginId, String login,
        String firstName, String name, String mail, String phone, String status, String role,
        String extraFields) throws IdentityProvisioningException {
    try {
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        String url = InweboConnectorConstants.INWEBO_URL;
        SOAPMessage soapResponse = soapConnection.call(createUserObject(userId, serviceId, loginId, login,
                firstName, name, mail, phone, status, role, extraFields), url);
        String updationStatus = soapResponse.getSOAPBody().getElementsByTagName("loginUpdateReturn").item(0)
                .getTextContent().toString();
        soapConnection.close();
        boolean processStatus = StringUtils.equals("OK", updationStatus);
        if (!processStatus) {
            String error = soapResponse.getSOAPBody().getElementsByTagName("loginUpdateReturn").item(0)
                    .getTextContent().toString();
            throw new IdentityProvisioningException(
                    "Error occurred while updating the user in InWebo:" + error);
        }
        return processStatus;
    } catch (SOAPException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    } catch (IdentityProvisioningException e) {
        throw new IdentityProvisioningException("Error occurred while sending SOAP Request to Server", e);
    }
}

From source file:test.functional.TestJAXMSamples.java

public void testJWSFault() throws Exception {
    try {//from w  ww. ja  v a  2  s . c om
        SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = scFactory.createConnection();

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

        SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
        SOAPBody body = envelope.getBody();

        Name bodyName = envelope.createName("echo");
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

        Name name = envelope.createName("arg0");
        SOAPElement symbol = bodyElement.addChildElement(name);
        symbol.addTextNode("Hello");

        URLEndpoint endpoint = new URLEndpoint("http://localhost:8080/jws/FaultTest.jws");
        SOAPMessage response = con.call(message, endpoint);
        SOAPBody respBody = response.getSOAPPart().getEnvelope().getBody();
        assertTrue(respBody.hasFault());
    } catch (javax.xml.soap.SOAPException e) {
        Throwable t = e.getCause();
        if (t != null) {
            t.printStackTrace();
            if (t instanceof AxisFault) {
                AxisFault af = (AxisFault) t;
                if ((af.detail instanceof SocketException)
                        || (af.getFaultCode().getLocalPart().equals("HTTP"))) {
                    System.out.println("Connect failure caused testJWSFault to be skipped.");
                    return;
                }
            }
            throw new Exception("Fault returned from test: " + t);
        } else {
            e.printStackTrace();
            throw new Exception("Exception returned from test: " + e);
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new Exception("Fault returned from test: " + t);
    }
}