Example usage for org.apache.http.auth AuthScope ANY_REALM

List of usage examples for org.apache.http.auth AuthScope ANY_REALM

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_REALM.

Prototype

String ANY_REALM

To view the source code for org.apache.http.auth AuthScope ANY_REALM.

Click Source Link

Document

The null value represents any realm.

Usage

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//w  ww .  j a  va 2s . c om
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

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

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client.//from  www .  j  a  v a  2  s .  c om
 *
 * @param basePath The base path for the class
 * @param resourceClass The JAX-RS Resource Class
 * @param method The JAX-RS Resource Class's method
 * @param model Configuration model
 */
public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) {
    Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
    _baseUri = createUri(basePath);
    if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class)
            && method.getReturnType().isInterface()) {
        _subResourcePath = createSubResourcePath(basePath, method);
    } else if (httpMethods == null || httpMethods.size() != 1) {
        throw RestEasyMessages.MESSAGES
                .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString());
    }
    _httpMethod = httpMethods.iterator().next();
    _resourceClass = resourceClass;
    _method = method;
    try {
        _uri = (UriBuilder) URIBUILDER_CLASS.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    }
    _uri.uri(_baseUri);
    if (_resourceClass.isAnnotationPresent(Path.class)) {
        _uri.path(_resourceClass);
    }
    if (_method.isAnnotationPresent(Path.class)) {
        _uri.path(_method);
    }

    _providerFactory = new ResteasyProviderFactory();

    boolean useBuiltins = true; // use builtin @Provider classes by default
    if (model.getContextParamsConfig() != null) {
        Map<String, String> contextParams = model.getContextParamsConfig().toMap();

        // Set use builtin @Provider classes
        String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS);
        if (registerBuiltins != null) {
            useBuiltins = Boolean.parseBoolean(registerBuiltins);
        }

        // Register @Provider classes
        List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams);
        if (providerClasses != null) {
            for (Class<?> pc : providerClasses) {
                _providerFactory.registerProvider(pc);
            }
        }

        List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams);
        if (interceptors != null) {
            for (ClientErrorInterceptor interceptor : interceptors) {
                _providerFactory.addClientErrorInterceptor(interceptor);
            }
        }
    }
    if (useBuiltins) {
        _providerFactory.setRegisterBuiltins(true);
        RegisterBuiltin.register(_providerFactory);
    }

    _extractorFactory = new DefaultEntityExtractorFactory();
    _extractor = _extractorFactory.createExtractor(_method);
    _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null);
    _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null);
    ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method);

    // Client executor
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = _baseUri.getPort();
    if (_baseUri.getScheme().startsWith("https")) {
        if (port == -1) {
            port = 443;
        }
        SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig());
        if (sslFactory == null) {
            sslFactory = SSLSocketFactory.getSocketFactory();
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory));
    } else {
        if (port == -1) {
            port = 80;
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpClient httpClient = new DefaultHttpClient(cm);
    _executor = new ApacheHttpClient4Executor(httpClient);
    // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory
    Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
            ClientExceptionMapper.class)[0];
    _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);

    // Authentication settings
    if (model.hasAuthentication()) {
        // Set authentication
        AuthScope authScope = null;
        Credentials credentials = null;
        if (model.isBasicAuth()) {
            authScope = createAuthScope(model.getBasicAuthConfig().getHost(),
                    model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm());
            credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(),
                    model.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
        } else {
            authScope = createAuthScope(model.getNtlmAuthConfig().getHost(),
                    model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm());
            credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(),
                    model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain());
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        ProxyModel proxy = model.getProxyConfig();
        if (proxy != null) {
            HttpHost proxyHost = null;
            if (proxy.getPort() != null) {
                proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue());
            } else {
                proxyHost = new HttpHost(proxy.getHost(), -1);
            }
            if (proxy.getUser() != null) {
                AuthScope authScope = new AuthScope(proxy.getHost(),
                        Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword());
                AuthCache authCache = new BasicAuthCache();
                authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY));
                ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope,
                        credentials);
                BasicHttpContext context = new BasicHttpContext();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
                ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
            }
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    }
    Integer timeout = model.getTimeout();
    if (timeout != null) {
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }
}

From source file:com.clustercontrol.http.util.GetHttpResponse.java

/**
 * URL??/*  ww  w .j ava 2  s .  co  m*/
 * 
 * @param url URL
 * @param timeout 
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws IOException
 * @throws ClientProtocolException
 */
public boolean execute(String url, String post) {
    Response result = new Response();
    try {
        CloseableHttpClient client = getHttpClient();

        result.url = url;
        if (m_authType != null && !AuthType.NONE.equals(m_authType)) {
            URI uri = new URI(url);

            Credentials credential = null;
            String authSchema = null;
            switch (m_authType) {
            case BASIC:
                credential = new UsernamePasswordCredentials(m_authUser, m_authPassword);
                authSchema = "basic";
                break;
            case NTLM:
                credential = new NTCredentials(m_authUser, m_authPassword, null, null);
                authSchema = "ntlm";
                break;
            case DIGEST:
                credential = new UsernamePasswordCredentials(m_authUser, m_authPassword);
                authSchema = "digest";
                break;
            default:
                m_log.warn("Auth type is unexpected value. AuthType = " + m_authType.name());
            }

            if (credential != null) {
                AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authSchema);
                if (m_cledentialProvider.getCredentials(scope) == null) {
                    m_cledentialProvider.setCredentials(scope, credential);
                }
            }
        }

        HttpRequestBase request = null;
        if (post != null && !post.isEmpty()) {
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();

            for (String ss : post.split("&")) {
                int index = ss.indexOf("=");
                if (index <= 0) {
                    continue;
                }
                urlParameters.add(new BasicNameValuePair(ss.substring(0, index), ss.substring(index + 1)));
            }
            if (m_log.isTraceEnabled()) {
                m_log.trace("post1=" + post + ", post2=" + urlParameters);
            }

            HttpPost requestPost = new HttpPost(url);
            Charset charset = Consts.UTF_8;
            try {
                charset = Charset.forName(
                        HinemosPropertyUtil.getHinemosPropertyStr("monitor.http.post.charset", "UTF-8"));
            } catch (UnsupportedCharsetException e) {
                m_log.warn("UnsupportedCharsetException " + e.getMessage());
            }
            requestPost.setEntity(new UrlEncodedFormEntity(urlParameters, charset));
            requestPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            request = requestPost;
        } else {
            request = new HttpGet(url);
        }

        // Execute the method.
        try {
            long start = HinemosTime.currentTimeMillis();
            HttpResponse response = client.execute(request);
            result.responseTime = HinemosTime.currentTimeMillis() - start;

            result.statusCode = response.getStatusLine().getStatusCode();

            // Header
            Header[] headers = response.getAllHeaders();
            if (headers != null && headers.length > 0) {
                StringBuffer header = new StringBuffer();
                for (int i = 0; i < headers.length; i++) {
                    header.append((i != 0 ? "\n" : "") + headers[i]);
                }
                result.headerString = header.toString();
                result.headers = Arrays.asList(headers);
            }

            if (result.statusCode == HttpStatus.SC_OK) {
                result.success = true;

                // Content-Type?text?????Body?
                Header header = response.getFirstHeader(HTTP.CONTENT_TYPE);

                boolean contentTypeFlag = false;
                String[] contentTypes = HinemosPropertyUtil
                        .getHinemosPropertyStr(TARGET_CONTENT_TYPE_KEY, "text").split(",");

                if (header != null && header.getValue() != null) {
                    String value = header.getValue();
                    for (String contentType : contentTypes) {
                        if (value.indexOf(contentType) != -1) {
                            contentTypeFlag = true;
                            break;
                        }
                    }
                }

                if (contentTypeFlag) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    try (InputStream in = response.getEntity().getContent()) {
                        byte[] buffer = new byte[BUFF_SIZE];
                        while (out.size() < BODY_MAX_SIZE) {
                            int len = in.read(buffer);
                            if (len < 0) {
                                break;
                            }
                            out.write(buffer, 0, len);
                        }
                    }

                    // ????HTTP ? meta ???????
                    // HTTP ??
                    //
                    // Content-Type: text/html; charset=euc-jp
                    //
                    // meta ?
                    //
                    // <meta http-equiv="Content-Type" content="text/html; charset=euc-jp">
                    // <meta charset="euc-jp">
                    //
                    // HTML ???meta ?????
                    //
                    // ????????????????
                    // ???????????????????
                    // ????????????????
                    //
                    // ??????????????????
                    //
                    // 1. HTTP ? Content-Type ? charset ????????
                    // ?????????
                    //
                    // 2. ????????"JISAutoDetect" ???
                    // ????
                    //
                    // 3. ??????meta ??
                    //
                    // 4. meta ??????????
                    // ????????
                    // ???????????

                    String charset = "JISAutoDetect";
                    Matcher m = chasetPattern.matcher(header.getValue());
                    if (m.matches())
                        charset = m.group(1);

                    String content = new String(out.toByteArray(), charset);

                    CharsetParser parser = new CharsetParser();
                    ParserDelegator p = new ParserDelegator();
                    p.parse(new StringReader(content), parser, true);

                    if (parser.charset != null && !charset.equals(parser.charset)) {
                        charset = parser.charset;
                        content = new String(out.toByteArray(), charset);
                    }
                    result.responseBody = content;
                } else {
                    result.errorMessage = MessageConstant.MESSAGE_FAIL_TO_CHECK_NOT_TEXT.getMessage();
                }
            } else {
                result.errorMessage = response.getStatusLine().toString();
            }
        } finally {
            request.releaseConnection();
        }
    } catch (UnsupportedEncodingException e) {
        m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName());
        result.errorMessage = "http receiving failure. (unsupported encoding)";
        result.exception = e;
    } catch (IOException e) {
        m_log.info("execute(): Fatal transport error. " + e.getMessage() + " class=" + e.getClass().getName());
        result.errorMessage = "http requesting failure. (I/O error : unreachable or timeout)";
        result.exception = e;
    } catch (Exception e) {
        m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName());
        result.errorMessage = "http requesting failure. " + e.getMessage() + "(" + e.getClass().getSimpleName()
                + ")";
        result.exception = e;
    }

    m_requestResult = result;

    return m_requestResult.success;
}

From source file:org.xwiki.android.rest.HttpConnector.java

/**
 * set user credentials with manually developed preemtive Auth
 *//* w w  w  .  j a  v a2  s  . co  m*/
private void setCredentials() {
    if (isSecured) {

        // Setting preemtiveAuth manually since org.apache.http does not support it
        preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };

        client.addRequestInterceptor(preemptiveAuth, 0);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM),
                defaultcreds);
    }
}

From source file:org.xwiki.android.test.utils.xmlrpc.RestClient.java

/**
 * set user credentials with manually developed preemtive Auth
 *//*from  w w w  .j a va2 s. c  om*/
private void setCredentials() {
    // Setting preemtiveAuth manually since org.apache.http does not support it
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);

                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }

    };
    client.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);

}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpsClient(String userName, String password) {
    try {//from w  ww. ja  v  a2  s  .  com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:org.artifactory.util.HttpClientConfigurator.java

private void configureProxy(ProxyDescriptor proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUsername() != null) {
            Credentials creds = null;/* w ww  .j a  v a  2s  .c om*/
            if (proxy.getDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUsername(),
                        CryptoHelper.decryptIfNeeded(proxy.getPassword()));
                //This will demote the NTLM authentication scheme so that the proxy won't barf
                //when we try to give it traditional credentials. If the proxy doesn't do NTLM
                //then this won't hurt it (jcej at tragus dot org)
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);
                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost = StringUtils.isBlank(proxy.getNtHost())
                            ? InetAddress.getLocalHost().getHostName()
                            : proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUsername(),
                            CryptoHelper.decryptIfNeeded(proxy.getPassword()), ntHost, proxy.getDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectedToHostsList() != null) {
                    for (String hostName : proxy.getRedirectedToHostsList()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}

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

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * // w  ww .  ja  va  2s  . c o  m
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

From source file:org.codelibs.fess.es.config.exentity.DataConfig.java

private AuthScope getAuthScope(final String webAuthName, final String scheme,
        final Map<String, String> paramMap) {
    final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
    final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
    final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
    AuthScope authScope;/*w w  w  .j  a v  a  2 s . c o  m*/
    if (StringUtil.isBlank(hostname)) {
        authScope = AuthScope.ANY;
    } else {
        int p = AuthScope.ANY_PORT;
        if (StringUtil.isNotBlank(port)) {
            try {
                p = Integer.parseInt(port);
            } catch (final NumberFormatException e) {
                logger.warn("Failed to parse " + port, e);
            }
        }

        String r = realm;
        if (StringUtil.isBlank(realm)) {
            r = AuthScope.ANY_REALM;
        }

        String s = scheme;
        if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
            s = AuthScope.ANY_SCHEME;
        }
        authScope = new AuthScope(hostname, p, r, s);
    }
    return authScope;
}