Example usage for javax.xml.ws Service createDispatch

List of usage examples for javax.xml.ws Service createDispatch

Introduction

In this page you can find the example usage for javax.xml.ws Service createDispatch.

Prototype

public Dispatch<Object> createDispatch(QName portName, JAXBContext context, Mode mode) 

Source Link

Document

Creates a Dispatch instance for use with JAXB generated objects.

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   www .  j  a va 2  s. c o 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:com.wavemaker.runtime.ws.HTTPBindingSupport.java

@SuppressWarnings("unchecked")
private static <T extends Object> T getResponse(QName serviceQName, QName portQName, String endpointAddress,
        HTTPRequestMethod method, T postSource, BindingProperties bindingProperties, Class<T> type,
        Map<String, Object> headerParams) throws WebServiceException {

    Service service = Service.create(serviceQName);
    URI endpointURI;//from   w  w  w .j a v  a 2  s .c o m
    try {
        if (bindingProperties != null) {
            // if BindingProperties had endpointAddress defined, then use
            // it instead of the endpointAddress passed in from arguments.
            String endAddress = bindingProperties.getEndpointAddress();
            if (endAddress != null) {
                endpointAddress = endAddress;
            }
        }
        endpointURI = new URI(endpointAddress);
    } catch (URISyntaxException e) {
        throw new WebServiceException(e);
    }

    String endpointPath = null;
    String endpointQueryString = null;
    if (endpointURI != null) {
        endpointPath = endpointURI.getRawPath();
        endpointQueryString = endpointURI.getRawQuery();
    }

    service.addPort(portQName, HTTPBinding.HTTP_BINDING, endpointAddress);

    Dispatch<T> d = service.createDispatch(portQName, type, Service.Mode.MESSAGE);

    Map<String, Object> requestContext = d.getRequestContext();
    requestContext.put(MessageContext.HTTP_REQUEST_METHOD, method.toString());
    requestContext.put(MessageContext.QUERY_STRING, endpointQueryString);
    requestContext.put(MessageContext.PATH_INFO, endpointPath);

    Map<String, List<String>> reqHeaders = null;
    if (bindingProperties != null) {
        String httpBasicAuthUsername = bindingProperties.getHttpBasicAuthUsername();
        if (httpBasicAuthUsername != null) {
            requestContext.put(BindingProvider.USERNAME_PROPERTY, httpBasicAuthUsername);
            String httpBasicAuthPassword = bindingProperties.getHttpBasicAuthPassword();
            requestContext.put(BindingProvider.PASSWORD_PROPERTY, httpBasicAuthPassword);
        }

        int connectionTimeout = bindingProperties.getConnectionTimeout();
        requestContext.put(JAXWSProperties.CONNECT_TIMEOUT, Integer.valueOf(connectionTimeout));

        int requestTimeout = bindingProperties.getRequestTimeout();
        requestContext.put(JAXWSProperties.REQUEST_TIMEOUT, Integer.valueOf(requestTimeout));

        Map<String, List<String>> httpHeaders = bindingProperties.getHttpHeaders();
        if (httpHeaders != null && !httpHeaders.isEmpty()) {
            reqHeaders = (Map<String, List<String>>) requestContext.get(MessageContext.HTTP_REQUEST_HEADERS);
            if (reqHeaders == null) {
                reqHeaders = new HashMap<String, List<String>>();
                requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
            }
            for (Entry<String, List<String>> entry : httpHeaders.entrySet()) {
                reqHeaders.put(entry.getKey(), entry.getValue());
            }
        }
    }

    // Parameters to pass in http header
    if (headerParams != null && headerParams.size() > 0) {
        if (null == reqHeaders) {
            reqHeaders = new HashMap<String, List<String>>();
        }
        Set<Entry<String, Object>> entries = headerParams.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            List<String> valList = new ArrayList<String>();
            valList.add((String) entry.getValue());
            reqHeaders.put(entry.getKey(), valList);
            requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
        }
    }

    logger.info("Invoking HTTP '" + method + "' request with URL: " + endpointAddress);

    T result = d.invoke(postSource);
    return result;
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public static synchronized Dispatch<Document> getDispatch() {
    if (dispatch == null) {
        Service service = Service.create(new QName(SOAPNS, "Service"));
        service.addPort(new QName(SOAPNS, "Port"), SOAPBinding.SOAP11HTTP_BINDING,
                ROOT + RPC_ROOT + apiVersion);

        dispatch = service.createDispatch(new QName(SOAPNS, "Port"), Document.class, Service.Mode.PAYLOAD);
        if (debug) {
            ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient().getEndpoint().getInInterceptors()
                    .add(new LoggingInInterceptor());
            ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient().getEndpoint().getOutInterceptors()
                    .add(new LoggingOutInterceptor());
        }// w  w  w .j a v  a  2 s . c  o  m
        HTTPConduit c = (HTTPConduit) ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient()
                .getConduit();
        HTTPClientPolicy clientPol = c.getClient();
        if (clientPol == null) {
            clientPol = new HTTPClientPolicy();
        }
        //CAMEL has a couple of HUGE HUGE pages that take a long time to render
        clientPol.setReceiveTimeout(5 * 60 * 1000);
        c.setClient(clientPol);

    }
    return dispatch;
}

From source file:com.mirth.connect.connectors.ws.WebServiceMessageDispatcher.java

private void createDispatch(MessageObject mo) throws Exception {
    String wsdlUrl = replacer.replaceValues(connector.getDispatcherWsdlUrl(), mo);
    String username = replacer.replaceValues(connector.getDispatcherUsername(), mo);
    String password = replacer.replaceValues(connector.getDispatcherPassword(), mo);
    String serviceName = replacer.replaceValues(connector.getDispatcherService(), mo);
    String portName = replacer.replaceValues(connector.getDispatcherPort(), mo);

    /*/*ww  w.java 2 s .  c  o m*/
     * The dispatch needs to be created if it hasn't been created yet
     * (null). It needs to be recreated if any of the above variables are
     * different than what were used to create the current dispatch object.
     * This could happen if variables are being used for these properties.
     */
    if (dispatch == null || !StringUtils.equals(wsdlUrl, currentWsdlUrl)
            || !StringUtils.equals(username, currentUsername) || !StringUtils.equals(password, currentPassword)
            || !StringUtils.equals(serviceName, currentServiceName)
            || !StringUtils.equals(portName, currentPortName)) {
        currentWsdlUrl = wsdlUrl;
        currentUsername = username;
        currentPassword = password;
        currentServiceName = serviceName;
        currentPortName = portName;

        URL endpointUrl = getWsdlUrl(wsdlUrl, username, password);
        QName serviceQName = QName.valueOf(serviceName);
        QName portQName = QName.valueOf(portName);

        // create the service and dispatch
        logger.debug("Creating web service: url=" + endpointUrl.toString() + ", service=" + serviceQName
                + ", port=" + portQName);
        Service service = Service.create(endpointUrl, serviceQName);

        dispatch = service.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);
    }
}

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

/**
 * @return//from ww  w.  j  a va2 s.  c o  m
 */
private Dispatch<SOAPMessage> getDispatch() {
    Service service = getService();
    Dispatch<SOAPMessage> dispatch = service.createDispatch(PORT_NAME, SOAPMessage.class, Service.Mode.MESSAGE);
    return dispatch;
}

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:com.legstar.proxy.invoke.jaxws.WebServiceInvoker.java

/**
 * Creates a JAX-WS dispatcher./*from   w ww  . j  av a 2  s .  c o m*/
 * 
 * @return an instance of jaxws dynamic client invoker.
 * @throws WebServiceInvokerException if attempt to instantiate dispatcher
 *             fails
 */
public Dispatch<Object> createDispatcher() throws WebServiceInvokerException {
    QName serviceQname = new QName(getWsdlTargetNamespace(), getWsdlServiceName());
    QName portQname = new QName(getWsdlTargetNamespace(), getWsdlPortName());
    Service service = Service.create(serviceQname);
    service.addPort(portQname, SOAPBinding.SOAP11HTTP_BINDING, getWsdlUrl());
    Dispatch<Object> dispatcher = service.createDispatch(portQname, createJAXBContext(), Service.Mode.PAYLOAD);

    if (_log.isDebugEnabled()) {
        _log.debug("New javax.xml.ws.Dispatch created for " + getWsdlServiceName());
    }
    return dispatcher;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

private void createDispatch(WebServiceDispatcherProperties webServiceDispatcherProperties,
        DispatchContainer dispatchContainer) throws Exception {
    String wsdlUrl = webServiceDispatcherProperties.getWsdlUrl();
    String username = webServiceDispatcherProperties.getUsername();
    String password = webServiceDispatcherProperties.getPassword();
    String serviceName = webServiceDispatcherProperties.getService();
    String portName = webServiceDispatcherProperties.getPort();

    /*//  w w w  .jav  a 2s . co m
     * The dispatch needs to be created if it hasn't been created yet (null). It needs to be
     * recreated if any of the above variables are different than what were used to create the
     * current dispatch object. This could happen if variables are being used for these
     * properties.
     */
    if (dispatchContainer.getDispatch() == null
            || !StringUtils.equals(wsdlUrl, dispatchContainer.getCurrentWsdlUrl())
            || !StringUtils.equals(username, dispatchContainer.getCurrentUsername())
            || !StringUtils.equals(password, dispatchContainer.getCurrentPassword())
            || !StringUtils.equals(serviceName, dispatchContainer.getCurrentServiceName())
            || !StringUtils.equals(portName, dispatchContainer.getCurrentPortName())) {
        dispatchContainer.setCurrentWsdlUrl(wsdlUrl);
        dispatchContainer.setCurrentUsername(username);
        dispatchContainer.setCurrentPassword(password);
        dispatchContainer.setCurrentServiceName(serviceName);
        dispatchContainer.setCurrentPortName(portName);

        URL endpointUrl = getWsdlUrl(dispatchContainer);
        QName serviceQName = QName.valueOf(serviceName);
        QName portQName = QName.valueOf(portName);

        // create the service and dispatch
        logger.debug("Creating web service: url=" + endpointUrl.toString() + ", service=" + serviceQName
                + ", port=" + portQName);
        Service service = Service.create(endpointUrl, serviceQName);

        Dispatch<SOAPMessage> dispatch = service.createDispatch(portQName, SOAPMessage.class,
                Service.Mode.MESSAGE);

        if (timeout > 0) {
            dispatch.getRequestContext().put("com.sun.xml.internal.ws.connect.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.internal.ws.request.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.ws.connect.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.ws.request.timeout", timeout);
        }

        Map<String, List<String>> requestHeaders = (Map<String, List<String>>) dispatch.getRequestContext()
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        if (requestHeaders == null) {
            requestHeaders = new HashMap<String, List<String>>();
        }
        dispatchContainer.setDefaultRequestHeaders(requestHeaders);

        dispatchContainer.setDispatch(dispatch);
    }
}

From source file:org.codice.ddf.security.claims.attributequery.common.AttributeQueryClaimsHandler.java

/**
 * Creates a dispatcher for dispatching requests.
 *///w ww . j a  v  a 2 s . co m
protected Dispatch<StreamSource> createDispatcher(Service service) {
    Dispatch<StreamSource> dispatch = null;
    if (service != null) {
        dispatch = service.createDispatch(QName.valueOf(portName), StreamSource.class, Service.Mode.MESSAGE);
        dispatch.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY, externalAttributeStoreUrl);
        dispatch.getRequestContext().put("ws-security.signature.properties", signatureProperties);
        dispatch.getRequestContext().put("ws-security.encryption.properties", encryptionProperties);
        ((DispatchImpl) dispatch).getClient().getBus().getOutInterceptors().add(new LoggingInInterceptor());
        ((DispatchImpl) dispatch).getClient().getBus().getOutInterceptors().add(new LoggingOutInterceptor());
    }
    return dispatch;
}