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:org.overlord.rtgov.tests.platforms.jbossas.slamonitor.JBossASSLAMonitorTest.java

@Test
@OperateOnDeployment("orders-app")
@Ignore// w ww . j  a v a  2s  .  c  om
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  .jav  a2 s.co 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 {// ww w .  j  a va  2s  .  co  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-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.pentaho.platform.plugin.action.xmla.XMLABaseComponent.java

@Override
protected boolean executeAction() {
    try {/* ww w.  j  a v  a 2 s  .  c  om*/
        scf = SOAPConnectionFactory.newInstance();
        mf = MessageFactory.newInstance();
    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } catch (SOAPException e) {
        e.printStackTrace();
    }

    String uri = this.getInputStringValue(XMLABaseComponent.URI);
    String user = this.getInputStringValue(XMLABaseComponent.USER);
    String password = this.getInputStringValue(XMLABaseComponent.PASSWORD);
    String catalog = this.getInputStringValue(XMLABaseComponent.CATALOG);
    String query = this.getInputStringValue(XMLABaseComponent.QUERY);

    buildURl(uri, user, password);
    try {
        setProviderAndDataSource(discoverDS());
        return executeQuery(query, catalog);
    } catch (XMLAException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

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;/* w w w  . j  a va 2 s .c om*/
    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 w ww.j av 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.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMappingTest.java

@Test
public void invoke() throws Exception {

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage request = messageFactory.createMessage();
    request.getSOAPBody().addBodyElement(QName.valueOf("{http://springframework.org/spring-ws}Request"));
    MessageContext messageContext = new DefaultMessageContext(new SaajSoapMessage(request),
            new SaajSoapMessageFactory(messageFactory));
    DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter();
    adapter.afterPropertiesSet();//from   w w w .j a va2s .co m

    MessageDispatcher messageDispatcher = new SoapMessageDispatcher();
    messageDispatcher.setApplicationContext(applicationContext);
    messageDispatcher.setEndpointMappings(Collections.<EndpointMapping>singletonList(mapping));
    messageDispatcher.setEndpointAdapters(Collections.<EndpointAdapter>singletonList(adapter));

    messageDispatcher.receive(messageContext);

    MyEndpoint endpoint = applicationContext.getBean("endpoint", MyEndpoint.class);
    assertTrue("doIt() not invoked on endpoint", endpoint.isDoItInvoked());

    LogAspect aspect = (LogAspect) applicationContext.getBean("logAspect");
    assertTrue("log() not invoked on aspect", aspect.isLogInvoked());
}

From source file:org.springframework.ws.soap.saaj.support.SaajUtils.java

/**
 * Checks whether we can find a SAAJ 1.2 implementation, being aware of the broken WebLogic 9 SAAJ implementation.
 * <p/>//from ww w .j a va2  s . c  om
 * WebLogic 9 does implement SAAJ 1.2, but throws UnsupportedOperationExceptions when a SAAJ 1.2 method is called.
 */
private static boolean isSaaj12() {
    if (Element.class.isAssignableFrom(SOAPElement.class)) {
        // see if we are dealing with WebLogic 9
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage message = messageFactory.createMessage();
            try {
                message.getSOAPBody();
                return true;
            } catch (UnsupportedOperationException ex) {
                return false;
            }
        } catch (SOAPException e) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.springframework.ws.transport.http.CommonsHttpMessageSenderIntegrationTest.java

@Test
public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();//w w w  .  j  a  v a  2 s .  c  om
    WebServiceConnection connection = null;
    try {

        StaticApplicationContext appContext = new StaticApplicationContext();
        appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class);
        appContext.refresh();

        CommonsHttpMessageSender messageSender = appContext.getBean("messageSender",
                CommonsHttpMessageSender.class);
        connection = messageSender.createConnection(new URI("http://localhost:" + port));

        appContext.close();

        connection.send(new SaajSoapMessage(messageFactory.createMessage()));
        connection.receive(new SaajSoapMessageFactory(messageFactory));
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (jettyServer.isRunning()) {
            jettyServer.stop();
        }
    }

}

From source file:org.wso2.caching.receivers.CacheMessageReceiver.java

/**
 * This method will be called when the message is received to the MR
 * and this will serve the response from the cache
 *
 * @param messageCtx - MessageContext to be served
 * @throws AxisFault if there is any error in serving from the cache
 *///from   ww  w . ja  v a  2 s.  c o m
public void receive(MessageContext messageCtx) throws AxisFault {

    MessageContext outMsgContext = MessageContextBuilder.createOutMessageContext(messageCtx);

    if (outMsgContext != null) {
        OperationContext opCtx = outMsgContext.getOperationContext();

        if (opCtx != null) {
            opCtx.addMessageContext(outMsgContext);
            if (log.isDebugEnabled()) {
                log.debug("Serving from the cache...");
            }

            Object cachedObj = opCtx.getPropertyNonReplicable(CachingConstants.CACHED_OBJECT);
            if (cachedObj != null && cachedObj instanceof CachableResponse) {
                try {
                    MessageFactory mf = MessageFactory.newInstance();
                    SOAPMessage smsg;
                    if (messageCtx.isSOAP11()) {
                        smsg = mf.createMessage(new MimeHeaders(),
                                new ByteArrayInputStream(((CachableResponse) cachedObj).getResponseEnvelope()));
                        ((CachableResponse) cachedObj).setInUse(false);
                    } else {
                        MimeHeaders mimeHeaders = new MimeHeaders();
                        mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
                        mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
                        smsg = mf.createMessage(mimeHeaders,
                                new ByteArrayInputStream(((CachableResponse) cachedObj).getResponseEnvelope()));
                        ((CachableResponse) cachedObj).setInUse(false);
                    }

                    if (smsg != null) {
                        org.apache.axiom.soap.SOAPEnvelope omSOAPEnv = SAAJUtil
                                .toOMSOAPEnvelope(smsg.getSOAPPart().getDocumentElement());
                        if (omSOAPEnv.getHeader() == null) {
                            SOAPFactory fac = getSOAPFactory(messageCtx);
                            fac.createSOAPHeader(omSOAPEnv);
                        }
                        outMsgContext.setEnvelope(omSOAPEnv);
                    } else {
                        handleException("Unable to serve from the cache : "
                                + "Couldn't build the SOAP response from the cached byte stream");
                    }

                } catch (SOAPException e) {
                    handleException("Unable to serve from the cache : "
                            + "Unable to get build the response from the byte stream", e);
                } catch (IOException e) {
                    handleException("Unable to serve from the cache : "
                            + "I/O Error in building the response envelope from the byte stream");
                }

                AxisEngine.send(outMsgContext);

            } else {
                handleException("Unable to find the response in the cache");
            }
        } else {
            handleException("Unable to serve from " + "the cache : OperationContext not found for processing");
        }
    } else {
        handleException("Unable to serve from " + "the cache : Unable to get the out message context");
    }
}