Example usage for javax.xml.ws Dispatch invoke

List of usage examples for javax.xml.ws Dispatch invoke

Introduction

In this page you can find the example usage for javax.xml.ws Dispatch invoke.

Prototype

public T invoke(T msg);

Source Link

Document

Invoke a service operation synchronously.

Usage

From source file:GoogleSearch.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://api.google.com/GoogleSearch.wsdl");
    QName serviceName = new QName("urn:GoogleSearch", "GoogleSearchService");
    QName portName = new QName("urn:GoogleSearch", "GoogleSearchPort");
    Service service = Service.create(url, serviceName);
    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);

    SOAPMessage request = MessageFactory.newInstance().createMessage(null,
            new FileInputStream("yourGoogleKey.xml"));

    SOAPMessage response = dispatch.invoke(request);
    response.writeTo(System.out);
}

From source file:com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * This class authenticates with the Hiperium Platform using JAXBContext and the selects user's home and
 * profile to access the system functions, and finally end the session. For all this lasts functions
 * we use SOAP messages with dispatchers and not JAXBContext.
 * //from  w w w  .ja  v  a 2s. co m
 * We need to recall, that for JAXBContext we could not add a handler to add header security parameters that need
 * to be verified in every service call in the Hiperium Platform, and for that reason, we only use JAXBContext in
 * the authentication process that do not need this header validation in the SOAP message header.
 * 
 * @param args
 */
public static void main(String[] args) {
    try {
        URL authURL = new URL(AUTH_SERVICE_URL);
        // The NAMESPACE must be http://authentication.soap.web.hiperium.com/ and must not begin
        // with http://SEI.authentication.soap.web.hiperium.com. Furthermore, the service name
        // and service port name must end WSService and WSPort respectively in order to call the service.
        QName authServiceQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSService");
        QName authPortQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSPort");
        // The parameter class must be annotated with @XmlRootElement in order to function
        JAXBContext jaxbContext = JAXBContext.newInstance(UserAuthentication.class,
                UserAuthenticationResponse.class);
        Service authService = Service.create(authURL, authServiceQName);
        // When we use JAXBContext the dispatcher mode must be PAYLOAD and NOT MESSAGE mode
        Dispatch<Object> dispatch = authService.createDispatch(authPortQName, jaxbContext,
                Service.Mode.PAYLOAD);
        UserCredentialDTO credentialsDTO = new UserCredentialDTO("andres_solorzano85@hotmail.com", "andres123");
        UserAuthentication authenticateRequest = new UserAuthentication();
        authenticateRequest.setArg0(credentialsDTO);
        UserAuthenticationResponse authenticateResponse = (UserAuthenticationResponse) dispatch
                .invoke(authenticateRequest);
        String sessionId = authenticateResponse.getReturn();
        LOGGER.debug("SESSION ID: " + sessionId);

        // Verify if session ID exists
        if (StringUtils.isNotBlank(sessionId)) {
            // Select home and profile
            URL selectHomeURL = new URL(HOME_SELECTION_SERVICE_URL);
            Service selectHomeService = Service.create(selectHomeURL,
                    new QName(AUTH_NAMESPACE, "HomeSelectionWSService"));
            selectHomeService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                    CLIENT_APPLICATION_TOKEN, AuthenticationObjectFactory._SelectHome_QNAME));
            Dispatch<SOAPMessage> selectHomeDispatch = selectHomeService.createDispatch(
                    new QName(AUTH_NAMESPACE, "HomeSelectionWSPort"), SOAPMessage.class, Service.Mode.MESSAGE);
            CommonsUtil.addSessionHeaderParms(selectHomeDispatch, sessionId);
            HomeSelectionDTO homeSelectionDTO = new HomeSelectionDTO(1L, 1L);
            SOAPMessage response = selectHomeDispatch.invoke(createSelectHomeSOAPMessage(homeSelectionDTO));
            readSOAPMessageResponse(response);

            // End Session
            URL endSessionURL = new URL(END_SESSION_SERVICE_URL);
            QName endSessionServiceQName = new QName(GENERAL_NAMESPACE, "MenuWSService");
            QName endSessionPortQName = new QName(GENERAL_NAMESPACE, "MenuWSPort");
            Service endSessionService = Service.create(endSessionURL, endSessionServiceQName);
            endSessionService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                    CLIENT_APPLICATION_TOKEN, GeneralObjectFactory._EndSession_QNAME));
            Dispatch<SOAPMessage> endSessionDispatch = endSessionService.createDispatch(endSessionPortQName,
                    SOAPMessage.class, Service.Mode.MESSAGE);
            CommonsUtil.addSessionHeaderParms(endSessionDispatch, sessionId);
            response = endSessionDispatch.invoke(createEndSessionSOAPMessage());
            readSOAPMessageResponse(response);
        }
    } catch (MalformedURLException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (JAXBException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void doMalformedStudyCheck()
        throws SOAPException, DOMException, IOException, SAXException, ParserConfigurationException {

    Dispatch<SOAPMessage> dispatch = getDispatch();

    // malformed study.
    try {//from  w  ww  . ja  va 2  s.  c o m
        dispatch.invoke(prepareImportRequestEnvelope("Study_Malformed"));
        fail("Malformed study went through.");
    } catch (SOAPFaultException e) {
        logger.info("Malformed study check passed.");
    }

    // malformed study # 2.
    try {
        dispatch.invoke(prepareImportRequestEnvelope("Study_Malformed2"));
        fail("Malformed study went through.");
    } catch (SOAPFaultException e) {
        logger.info("Malformed study check passed.");
    }

}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void doUnopenableStudyCheck()
        throws SOAPException, DOMException, IOException, SAXException, ParserConfigurationException {
    String xmlFile = "Study_Unopenable";
    Dispatch<SOAPMessage> dispatch = getDispatch();

    // study cannot be opened. biz checks must fail.
    try {/*from   w  w  w  .  j av  a  2s . c o m*/
        dispatch.invoke(prepareImportRequestEnvelope(xmlFile));
        fail("Unopenable study went through.");
    } catch (SOAPFaultException e) {
        logger.info("Unopenable study check passed.");
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void doDuplicateStudyCheck()
        throws SOAPException, DOMException, IOException, SAXException, ParserConfigurationException {
    String xmlFile = "Study";
    Dispatch<SOAPMessage> dispatch = getDispatch();

    // duplicate study: second request with same study must fail
    try {//w  ww .  ja va2  s .c  o  m
        dispatch.invoke(prepareImportRequestEnvelope(xmlFile));
        fail("Duplicate study went through.");
    } catch (SOAPFaultException e) {
        logger.info("Duplicate study check passed.");
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

/**
 * @throws Exception/*from  w w w . j ava  2 s .  c  om*/
 * @throws DatabaseUnitException
 * @throws SQLException
 * @throws DataSetException
 * 
 */
private void doSuccessfulImportStudyCheck()
        throws DataSetException, SQLException, DatabaseUnitException, Exception {
    String xmlFile = "Study";

    // successful study save.
    Dispatch<SOAPMessage> dispatch = getDispatch();
    SOAPMessage reqMsg = prepareImportRequestEnvelope(xmlFile);
    SOAPMessage respMsg = dispatch.invoke(reqMsg);
    verifySuccessulImportResponse(respMsg);

    // verify database data.
    verifyStudyDatabaseData("");
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void doStudyExportCheck()
        throws DOMException, SOAPException, IOException, SAXException, ParserConfigurationException {
    String xmlFile = "StudyIdentifier";

    Dispatch<SOAPMessage> dispatch = getDispatch();
    SOAPMessage reqMsg = prepareExportRequestEnvelope(xmlFile);
    SOAPMessage respMsg = dispatch.invoke(reqMsg);

    SOAPPart part = respMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, "ExportStudyResponse");
    assertEquals(1, nodes.getLength());//from  w  w w.jav a 2 s . c  o m
    Element responseEl = (Element) nodes.item(0);
    assertEquals(1, responseEl.getChildNodes().getLength());

    Element exportedStudy = (Element) responseEl.getChildNodes().item(0);
    // this study element must match the one used to create the study in the first place
    Element originalStudy = (Element) getSOAPBodyFromXML("Study");
    assertTrue(XMLUtils.isDeepEqual(exportedStudy, originalStudy));

}

From source file:test.integ.be.fedict.hsm.ws.WSS4JTest.java

@Test
public void testSecurity() throws Exception {
    QName serviceName = new QName("http://www.example.com/test", "TestService");
    Service service = Service.create(serviceName);
    QName portName = new QName("http://www.example.com/test", "TestPort");
    String endpointAddress = this.baseURL + "test";
    LOG.debug("endpoint address: " + endpointAddress);
    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    BindingProvider bindingProvider = (BindingProvider) dispatch;
    SOAPBinding soapBinding = (SOAPBinding) bindingProvider.getBinding();
    List handlerChain = soapBinding.getHandlerChain();
    handlerChain.add(new WSS4JTestSOAPHandler());
    soapBinding.setHandlerChain(handlerChain);
    MessageFactory messageFactory = soapBinding.getMessageFactory();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPBody soapBody = soapMessage.getSOAPBody();
    QName payloadName = new QName("http://www.example.com/test", "Payload", "prefix");
    SOAPBodyElement soapBodyElement = soapBody.addBodyElement(payloadName);
    soapBodyElement.addTextNode("hello world");

    SOAPMessage replyMessage = dispatch.invoke(soapMessage);
}

From source file:eu.domibus.ebms3.sender.MSHDispatcher.java

public SOAPMessage dispatch(final SOAPMessage soapMessage, final String pModeKey) throws EbMS3Exception {

    final QName serviceName = new QName("http://domibus.eu", "msh-dispatch-service");
    final QName portName = new QName("http://domibus.eu", "msh-dispatch");
    final javax.xml.ws.Service service = javax.xml.ws.Service.create(serviceName);
    final String endpoint = pModeProvider.getReceiverParty(pModeKey).getEndpoint();
    service.addPort(portName, SOAPBinding.SOAP12HTTP_BINDING, endpoint);
    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class,
            javax.xml.ws.Service.Mode.MESSAGE);

    Policy policy = policyFactory
            .parsePolicy(pModeProvider.getLegConfiguration(pModeKey).getSecurity().getPolicy());
    LegConfiguration legConfiguration = pModeProvider.getLegConfiguration(pModeKey);
    dispatch.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, policy);
    dispatch.getRequestContext().put(ASYMMETRIC_SIG_ALGO_PROPERTY,
            legConfiguration.getSecurity().getSignatureMethod().getAlgorithm());
    dispatch.getRequestContext().put(PMODE_KEY_CONTEXT_PROPERTY, pModeKey);

    TLSClientParameters params = tlsReader.getTlsClientParameters();
    if (params != null && endpoint.startsWith("https://")) {
        Client client = ((DispatchImpl<SOAPMessage>) dispatch).getClient();
        HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
        httpConduit.setTlsClientParameters(params);
    }/*from w  w  w  . ja va 2  s.c o m*/
    SOAPMessage result;
    try {
        result = dispatch.invoke(soapMessage);
    } catch (WebServiceException e) {
        throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0005, null,
                "error dispatching message to " + endpoint, e, MSHRole.SENDING);
    }
    return result;
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokeSOAP(Element request, List<Element> headers, int retries, String protocol,
        int connectTimeoutMS, int requestTimeoutMS) throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request));

    // if the service is null here because the WSDL is unavailable, 
    // create a plain HTTP POST invocation..
    if (service == null) {
        return doInvokePOST(request, new HashMap<String, String>(), retries);
    }/*from   ww  w. j  a v  a2  s.  com*/

    Dispatch<SOAPMessage> dispatch = null;
    synchronized (service) {
        dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    }

    dispatch.getRequestContext().put("com.sun.xml.ws.connect.timeout", connectTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.ws.request.timeout", requestTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.internal.ws.connect.timeout", connectTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.internal.ws.request.timeout", requestTimeoutMS);
    dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
            Collections.singletonMap("Connection", Collections.singletonList("close")));

    try {
        SOAPMessage message = createSOAPMessage(request, headers, protocol);
        String tmpID = PerformanceInterceptor.event(EventType.START_SEND_INVOCATION);
        SOAPMessage response = dispatch.invoke(message);
        PerformanceInterceptor.event(EventType.FINISH_SEND_INVOCATION, tmpID);
        InvocationResult result = new InvocationResult(response.getSOAPBody());
        return result;
    } catch (Exception e) {
        if (!(e.getCause() instanceof ThreadDeath)) {
            //logger.warn("Exception in invocation; to: " + endpointURL + "; " + e);
        }

        if (retries <= 0) {
            throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request), e);
        }
        if (e instanceof BindException || e.getCause() instanceof BindException) {
            long sleep = 200L + (long) (Math.random() * 800);
            logger.warn("Cannot bind to (client) port, sleeping " + sleep);
            Thread.sleep(sleep);
        }
        request = xmlUtil.clone(request);
        return doInvokeSOAP(request, headers, retries - 1, protocol, connectTimeoutMS, requestTimeoutMS);
    } finally {
        //PerformanceInterceptor.event(EventType.FINISH_INVOCATION, eID);
        //System.out.println(eID + " finished " + endpointURL);
    }
}