Example usage for javax.xml.ws BindingProvider PASSWORD_PROPERTY

List of usage examples for javax.xml.ws BindingProvider PASSWORD_PROPERTY

Introduction

In this page you can find the example usage for javax.xml.ws BindingProvider PASSWORD_PROPERTY.

Prototype

String PASSWORD_PROPERTY

To view the source code for javax.xml.ws BindingProvider PASSWORD_PROPERTY.

Click Source Link

Document

Standard property: Password for authentication.

Usage

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 ava  2s  .  c  om*/
    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.systest.http_jetty.JettyDigestAuthTest.java

private void doTest(boolean async) throws Exception {
    setupClient(async);//from  ww w.  j ava  2 s  . c  om
    assertEquals("Hello Alice", greeter.greetMe("Alice"));
    assertEquals("Hello Bob", greeter.greetMe("Bob"));

    try {
        BindingProvider bp = (BindingProvider) greeter;
        if (async) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials("blah", "foo");
            bp.getRequestContext().put(Credentials.class.getName(), creds);
        } else {
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "blah");
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "foo");
        }
        greeter.greetMe("Alice");
        fail("Password was wrong, should have failed");
    } catch (WebServiceException wse) {
        //ignore - expected
    }
}

From source file:Java_BWS_Sample.SampleBwsClient.java

/*******************************************************************************************************************
 *
 * Initialize the BWS and BWSUtil services.
 *
 * @return Returns true when the setup is successful, and false otherwise.
 *
 *******************************************************************************************************************
 *///w w  w.  j  a va  2s.c  om
private static boolean setup() {
    final String METHOD_NAME = "setup()";
    logMessage("Entering %s", METHOD_NAME);
    boolean returnValue = false;
    REQUEST_METADATA.setClientVersion(CLIENT_VERSION);
    REQUEST_METADATA.setLocale(LOCALE);
    REQUEST_METADATA.setOrganizationUid(ORG_UID);

    URL bwsServiceUrl = null;
    URL bwsUtilServiceUrl = null;

    try {
        // These are the URLs that point to the web services used for all calls.
        bwsServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/ws");
        bwsUtilServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/util/ws");
    } catch (MalformedURLException e) {

        logMessage("Cannot initialize web service URLs");
        logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
        return returnValue;
    }

    // Initialize the BWS web service stubs that will be used for all calls.
    logMessage("Initializing BWS web service stub");
    QName serviceBWS = new QName("http://ws.rim.com/enterprise/admin", "BWSService");
    QName portBWS = new QName("http://ws.rim.com/enterprise/admin", "BWS");
    _bwsService = new BWSService(null, serviceBWS);
    _bwsService.addPort(portBWS, "http://schemas.xmlsoap.org/soap/", bwsServiceUrl.toString());
    _bws = _bwsService.getPort(portBWS, BWS.class);
    logMessage("BWS web service stub initialized");

    logMessage("Initializing BWSUtil web service stub");
    QName serviceUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtilService");
    QName portUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtil");
    _bwsUtilService = new BWSUtilService(null, serviceUtil);
    _bwsUtilService.addPort(portUtil, "http://schemas.xmlsoap.org/soap/", bwsUtilServiceUrl.toString());
    _bwsUtil = _bwsUtilService.getPort(portUtil, BWSUtil.class);
    logMessage("BWSUtil web service stub initialized");
    // Set the connection timeout to 60 seconds.
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout(60000);

    httpClientPolicy.setAllowChunking(false);
    httpClientPolicy.setReceiveTimeout(60000);

    Client client = ClientProxy.getClient(_bws);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    client = ClientProxy.getClient(_bwsUtil);
    http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    Authenticator authenticator = getAuthenticator(AUTHENTICATOR_NAME);
    if (authenticator != null) {
        String encodedUsername = getEncodedUserName(USERNAME, authenticator);
        if (encodedUsername != null && !encodedUsername.isEmpty()) {
            /*
             * Set the HTTP basic authentication on the BWS service.
             * BWSUtilService is a utility web service that does not require
             * authentication.
             */
            BindingProvider bp = (BindingProvider) _bws;
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, encodedUsername);
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);

            returnValue = true;
        } else {
            logMessage("'encodedUsername' is null or empty");
        }
    } else {
        logMessage("'authenticator' is null");
    }

    logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
    return returnValue;
}

From source file:com.clustercontrol.util.EndpointUnit.java

private void setBindingProvider(Object o, String url) {
    BindingProvider bp = (BindingProvider) o;
    bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
    bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userId);
    bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
    bp.getRequestContext().put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 8192);

    // Maximum time between establishing a connection and receiving data from the connection (ms)
    int httpRequestTimeout = EndpointManager.getHttpRequestTimeout();
    bp.getRequestContext().put(BindingProviderProperties.REQUEST_TIMEOUT, httpRequestTimeout);
    if (m_log.isTraceEnabled()) {
        m_log.trace("ws timeout updated : requestTimeout = " + httpRequestTimeout + "");
    }/* w  ww . j  av a 2  s.  c o  m*/

    ((SOAPBinding) bp.getBinding()).setMTOMEnabled(true);
}

From source file:com.amalto.workbench.utils.Util.java

public static TMDMService getMDMService(URL url, final String username, final String password,
        boolean showMissingJarDialog) throws XtentisException {
    url = checkAndAddSuffix(url);//from   ww  w  . j av a  2s  .  co  m

    boolean needCheck = true;
    TMDMService service = (TMDMService) cachedMDMService.get(url, username, password);
    if (service == null) {
        needCheck = false;

        boolean checkResult = MissingJarService.getInstance().checkMissingJar(showMissingJarDialog);
        if (!checkResult) {
            throw new MissingJarsException("Missing dependency libraries."); //$NON-NLS-1$
        }

        try {

            TMDMService_Service service_service = new TMDMService_Service(url);

            service = service_service.getTMDMPort();

            BindingProvider stub = (BindingProvider) service;

            // Do not maintain session via cookies
            stub.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, false);

            Map<String, Object> context = stub.getRequestContext();
            // // dynamic set endpointAddress
            // context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);

            // authentication
            context.put(BindingProvider.USERNAME_PROPERTY, username);
            context.put(BindingProvider.PASSWORD_PROPERTY, password);

            IWebServiceHook wsHook = getWebServiceHook();
            if (wsHook != null) {
                wsHook.preRequestSendingHook(stub, username);
            }

            cachedMDMService.put(url, username, password, service);
        } catch (WebServiceException e) {
            XtentisException ex = convertWebServiceException(e);
            log.error(Messages.bind(Messages.UnableAccessEndpoint, url, e.getMessage()), e);
            if (ex != null) {
                throw ex;
            }
        }

    }

    if (needCheck) {
        try {
            service.ping(new WSPing());
        } catch (WebServiceException e) {
            cachedMDMService.remove(url, username, password);

            XtentisException ex = convertWebServiceException(e);
            log.error(Messages.bind(Messages.UnableAccessEndpoint, url, e.getMessage()), e);
            if (ex != null) {
                throw ex;
            }
        }
    }

    return service;
}

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

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    WebServiceDispatcherProperties webServiceDispatcherProperties = (WebServiceDispatcherProperties) connectorProperties;

    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING));

    String responseData = null;//from w  ww  . j  ava 2 s  .  c o m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    try {
        long dispatcherId = getDispatcherId();
        DispatchContainer dispatchContainer = dispatchContainers.get(dispatcherId);
        if (dispatchContainer == null) {
            dispatchContainer = new DispatchContainer();
            dispatchContainers.put(dispatcherId, dispatchContainer);
        }

        /*
         * Initialize the dispatch object if it hasn't been initialized yet, or create a new one
         * if the connector properties have changed due to variables.
         */
        createDispatch(webServiceDispatcherProperties, dispatchContainer);

        Dispatch<SOAPMessage> dispatch = dispatchContainer.getDispatch();

        configuration.configureDispatcher(this, webServiceDispatcherProperties, dispatch.getRequestContext());

        SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

        if (webServiceDispatcherProperties.isUseAuthentication()) {
            String currentUsername = dispatchContainer.getCurrentUsername();
            String currentPassword = dispatchContainer.getCurrentPassword();

            dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
            dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
            logger.debug("Using authentication: username=" + currentUsername + ", password length="
                    + currentPassword.length());
        }

        // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
        String soapAction = webServiceDispatcherProperties.getSoapAction();

        if (StringUtils.isNotEmpty(soapAction)) {
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, true); // MIRTH-2109
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
        }

        // Get default headers
        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(
                dispatchContainer.getDefaultRequestHeaders());

        // Add custom headers
        if (MapUtils.isNotEmpty(webServiceDispatcherProperties.getHeaders())) {
            for (Entry<String, List<String>> entry : webServiceDispatcherProperties.getHeaders().entrySet()) {
                List<String> valueList = requestHeaders.get(entry.getKey());

                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    requestHeaders.put(entry.getKey(), valueList);
                }

                valueList.addAll(entry.getValue());
            }
        }

        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);

        // build the message
        logger.debug("Creating SOAP envelope.");
        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();
        String content = attachmentHandlerProvider.reAttachMessage(webServiceDispatcherProperties.getEnvelope(),
                connectorMessage);
        Source source = new StreamSource(new StringReader(content));
        SOAPMessage message = soapBinding.getMessageFactory().createMessage();
        message.getSOAPPart().setContent(source);

        if (webServiceDispatcherProperties.isUseMtom()) {
            soapBinding.setMTOMEnabled(true);

            List<String> attachmentIds = webServiceDispatcherProperties.getAttachmentNames();
            List<String> attachmentContents = webServiceDispatcherProperties.getAttachmentContents();
            List<String> attachmentTypes = webServiceDispatcherProperties.getAttachmentTypes();

            for (int i = 0; i < attachmentIds.size(); i++) {
                String attachmentContentId = attachmentIds.get(i);
                String attachmentContentType = attachmentTypes.get(i);
                String attachmentContent = attachmentHandlerProvider.reAttachMessage(attachmentContents.get(i),
                        connectorMessage);

                AttachmentPart attachment = message.createAttachmentPart();
                attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                        attachmentContentType);
                attachment.setContentId(attachmentContentId);
                message.addAttachmentPart(attachment);
            }
        }

        message.saveChanges();

        if (StringUtils.isNotBlank(webServiceDispatcherProperties.getLocationURI())) {
            dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                    webServiceDispatcherProperties.getLocationURI());
        }

        boolean redirect = false;
        int tryCount = 0;

        /*
         * Attempt the invocation until we hit the maximum allowed redirects. The redirections
         * we handle are when the scheme changes (i.e. from HTTP to HTTPS).
         */
        do {
            redirect = false;
            tryCount++;

            try {
                DispatchTask<SOAPMessage> task = new DispatchTask<SOAPMessage>(dispatch, message,
                        webServiceDispatcherProperties.isOneWay());
                SOAPMessage result;

                /*
                 * If the timeout is set to zero, we need to do the invocation in a separate
                 * thread. This is because there's no way to get a reference to the underlying
                 * JAX-WS socket, so there's no way to forcefully halt the dispatch. If the
                 * socket is truly hung and the user halts the channel, the best we can do is
                 * just interrupt and ignore the thread. This means that a thread leak is
                 * potentially introduced, so we need to notify the user appropriately.
                 */
                if (timeout == 0) {
                    // Submit the task to an executor so that it's interruptible
                    Future<SOAPMessage> future = executor.submit(task);
                    // Keep track of the task by adding it to our set
                    dispatchTasks.add(task);
                    result = future.get();
                } else {
                    // Call the task directly
                    result = task.call();
                }

                if (webServiceDispatcherProperties.isOneWay()) {
                    responseStatusMessage = "Invoked one way operation successfully.";
                } else {
                    responseData = sourceToXmlString(result.getSOAPPart().getContent());
                    responseStatusMessage = "Invoked two way operation successfully.";
                }
                logger.debug("Finished invoking web service, got result.");

                // Automatically accept message; leave it up to the response transformer to find SOAP faults
                responseStatus = Status.SENT;
            } catch (Throwable e) {
                // Unwrap the exception if it came from the executor
                if (e instanceof ExecutionException && e.getCause() != null) {
                    e = e.getCause();
                }

                // If the dispatch was interrupted, make sure to reset the interrupted flag
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }

                Integer responseCode = null;
                String location = null;

                if (dispatch.getResponseContext() != null) {
                    responseCode = (Integer) dispatch.getResponseContext()
                            .get(MessageContext.HTTP_RESPONSE_CODE);

                    Map<String, List<String>> headers = (Map<String, List<String>>) dispatch
                            .getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
                    if (MapUtils.isNotEmpty(headers)) {
                        List<String> locations = headers.get("Location");
                        if (CollectionUtils.isNotEmpty(locations)) {
                            location = locations.get(0);
                        }
                    }
                }

                if (tryCount < MAX_REDIRECTS && responseCode != null && responseCode >= 300
                        && responseCode < 400 && StringUtils.isNotBlank(location)) {
                    redirect = true;

                    // Replace the endpoint with the redirected URL
                    dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);
                } else {
                    // Leave the response status as QUEUED for NoRouteToHostException and ConnectException, otherwise ERROR
                    if (e instanceof NoRouteToHostException
                            || ((e.getCause() != null) && (e.getCause() instanceof NoRouteToHostException))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("HTTP transport error",
                                e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "HTTP transport error", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "HTTP transport error.", e));
                    } else if ((e.getClass() == ConnectException.class) || ((e.getCause() != null)
                            && (e.getCause().getClass() == ConnectException.class))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Connection refused.",
                                e);
                        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR,
                                getDestinationName(), connectorProperties.getName(), "Connection refused.", e));
                    } else {
                        if (e instanceof SOAPFaultException) {
                            try {
                                responseData = new DonkeyElement(((SOAPFaultException) e).getFault()).toXml();
                            } catch (DonkeyElementException e2) {
                            }
                        }
                        responseStatus = Status.ERROR;
                        responseStatusMessage = ErrorMessageBuilder
                                .buildErrorResponse("Error invoking web service", e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "Error invoking web service", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "Error invoking web service.", e));
                    }
                }
            }
        } while (redirect && tryCount < MAX_REDIRECTS);
    } catch (Exception e) {
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error creating web service dispatch",
                e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error creating web service dispatch", e);
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error creating web service dispatch.", e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:edu.ku.kuali.kra.award.sapintegration.SapIntegrationServiceImpl.java

/**
 * Configures the service endpoint by configuring basic http authentication
 * on the service as well as setting a custom value for the service endpoint
 * if one has been configured.//from   w w  w  .  j  a  va 2 s.  c  o m
 */
protected void configureServiceEndpoint(SIKCRMPROCESSOUTBOUND serviceEndpoint, PrintWriter sendWriter,
        PrintWriter receiveWriter) {

    Client client = ClientProxy.getClient(serviceEndpoint);
    client.getOutInterceptors().add(new LoggingOutInterceptor(sendWriter));
    client.getInInterceptors().add(new LoggingInInterceptor(receiveWriter));

    String connectionTimeout = ConfigContext.getCurrentContextConfig()
            .getProperty(SAP_SERVICE_CONNECTION_TIMEOUT_PARAM);
    String receiveTimeout = ConfigContext.getCurrentContextConfig()
            .getProperty(SAP_SERVICE_RECEIVE_TIMEOUT_PARAM);
    if (!StringUtils.isBlank(connectionTimeout) || !StringUtils.isBlank(receiveTimeout)) {
        Conduit conduit = client.getConduit();
        if (conduit instanceof HTTPConduit) {
            HTTPConduit httpConduit = (HTTPConduit) conduit;
            HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
            if (!StringUtils.isBlank(connectionTimeout)) {
                httpClientPolicy.setConnectionTimeout(Long.parseLong(connectionTimeout));
            }
            if (!StringUtils.isBlank(receiveTimeout)) {
                httpClientPolicy.setReceiveTimeout(Long.parseLong(receiveTimeout));
            }
            httpConduit.setClient(httpClientPolicy);
        }
    }

    if (!(serviceEndpoint instanceof BindingProvider)) {
        throw new IllegalArgumentException(
                "The given service endpoint should be an instance of BindingProvider but was not.");
    }
    BindingProvider provider = (BindingProvider) serviceEndpoint;
    Map<String, Object> requestContext = provider.getRequestContext();

    String username = ConfigContext.getCurrentContextConfig().getProperty(SAP_SERVICE_USERNAME_PARAM);
    String password = ConfigContext.getCurrentContextConfig().getProperty(SAP_SERVICE_PASSWORD_PARAM);

    if (StringUtils.isBlank(username)) {
        throw new IllegalStateException(
                "No username was configured for the SAP service, please ensure that the following configuration parameter is set: "
                        + SAP_SERVICE_USERNAME_PARAM);
    }
    if (StringUtils.isBlank(password)) {
        throw new IllegalStateException(
                "No passwrod was configured for the SAP service, please ensure that the following configuration parameter is set: "
                        + SAP_SERVICE_PASSWORD_PARAM);
    }

    requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
    requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);

    // next check if a custom endpoint url has been configured
    String endpointUrl = ConfigContext.getCurrentContextConfig().getProperty(SAP_SERVICE_URL_PARAM);
    if (!StringUtils.isBlank(endpointUrl)) {
        requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl);
    }

}

From source file:codesample.AuthenticationSample.java

/*****************************************************************************************************************
 *
 * Initialize the BWS and BWSUtil services.
 *
 * @return Returns true when the setup is successful, and false otherwise.
 *
 *****************************************************************************************************************
 *///ww w.j a v  a2s.c o m
private static boolean setup(String hostname, String bwsPort, String username, String password,
        String authenticatorName, CredentialType credentialType, String domain) {
    final String METHOD_NAME = "setup()";
    logMessage("Entering %s", METHOD_NAME);
    boolean returnValue = false;
    REQUEST_METADATA.setClientVersion(CLIENT_VERSION);
    REQUEST_METADATA.setLocale(LOCALE);
    REQUEST_METADATA.setOrganizationUid(ORG_UID);

    URL bwsServiceUrl = null;
    URL bwsUtilServiceUrl = null;

    try {
        // These are the URLs that point to the web services used for all calls.
        // e.g. with no port:
        // https://server01.example.net/enterprise/admin/ws
        // e.g. with port:
        // https://server01.example.net:38443/enterprise/admin/ws
        String port = "";

        if (bwsPort != null) {
            port = ":" + bwsPort;
        }

        bwsServiceUrl = new URL("https://" + hostname + port + "/enterprise/admin/ws");
        bwsUtilServiceUrl = new URL("https://" + hostname + port + "/enterprise/admin/util/ws");

    } catch (MalformedURLException e) {
        logMessage("Cannot initialize web service URLs");
        logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
        return returnValue;
    }

    // Initialize the BWS web service stubs that will be used for all calls.
    logMessage("Initializing BWS web service stub");
    QName serviceBWS = new QName("http://ws.rim.com/enterprise/admin", "BWSService");
    QName portBWS = new QName("http://ws.rim.com/enterprise/admin", "BWS");
    _bwsService = new BWSService(null, serviceBWS);
    _bwsService.addPort(portBWS, "http://schemas.xmlsoap.org/soap/", bwsServiceUrl.toString());
    _bws = _bwsService.getPort(portBWS, BWS.class);
    logMessage("BWS web service stub initialized");

    logMessage("Initializing BWSUtil web service stub");
    QName serviceUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtilService");
    QName portUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtil");
    _bwsUtilService = new BWSUtilService(null, serviceUtil);
    _bwsUtilService.addPort(portUtil, "http://schemas.xmlsoap.org/soap/", bwsUtilServiceUrl.toString());
    _bwsUtil = _bwsUtilService.getPort(portUtil, BWSUtil.class);
    logMessage("BWSUtil web service stub initialized");
    // Set the connection timeout to 60 seconds.
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout(60000);

    httpClientPolicy.setAllowChunking(false);
    httpClientPolicy.setReceiveTimeout(60000);

    Client client = ClientProxy.getClient(_bws);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    client = ClientProxy.getClient(_bwsUtil);
    http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    Authenticator authenticator = getAuthenticator(authenticatorName);
    if (authenticator != null) {
        String encodedUsername = getEncodedUserName(username, authenticator, credentialType, domain);
        if (encodedUsername != null && !encodedUsername.isEmpty()) {
            /*
             * Set the HTTP basic authentication on the BWS service. BWSUtilService is a utility web service that
             * does not require authentication.
             */
            BindingProvider bp = (BindingProvider) _bws;
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, encodedUsername);
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

            returnValue = true;
        } else {
            logMessage("\"encodedUsername\" is null or empty");
        }
    } else {
        logMessage("\"authenticator\" is null");
    }

    logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
    return returnValue;
}

From source file:com.docdoku.client.actions.MainController.java

public void login(String login, String password, String workspaceId) throws Exception {
    try {//w  w w.  j ava2  s  .  com
        ((BindingProvider) mDocumentService).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, login);
        ((BindingProvider) mDocumentService).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
                password);
        ((BindingProvider) mWorkflowService).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, login);
        ((BindingProvider) mWorkflowService).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
                password);
        ((BindingProvider) mFileService).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, login);
        ((BindingProvider) mFileService).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
        mDocumentService.whoAmI(workspaceId);
        MainModel.init(login, password, workspaceId, mDocumentService, mWorkflowService, mFileService);
    } catch (WebServiceException pWSEx) {
        Throwable t = pWSEx.getCause();
        if (t instanceof Exception) {
            throw (Exception) t;
        } else {
            throw pWSEx;
        }
    }
}