Example usage for org.apache.http.auth NTCredentials NTCredentials

List of usage examples for org.apache.http.auth NTCredentials NTCredentials

Introduction

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

Prototype

public NTCredentials(final String userName, final String password, final String workstation,
        final String domain) 

Source Link

Document

Constructor.

Usage

From source file:my.madet.function.HttpParser.java

public String FetchUrL(String url) {
    StringBuffer result = new StringBuffer();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w ww. j a va  2s.  c  o m*/
        // register ntlm auth scheme
        httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("info.uniten.edu.my", AuthScope.ANY_PORT),
                new NTCredentials(unitenid, unitenpassw, "", ""));

        HttpGet request = new HttpGet(url);
        HttpResponse httpResponse = httpclient.execute(request);

        BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

        String line = "";
        while ((line = br.readLine()) != null) {
            result.append(line);
        }

        br.close();

    } catch (UnknownHostException e) { // no internet connection catch
        e.printStackTrace();
        Log.e("FetchUrL", "No internet ");
        return "No_Internet";
    } catch (Exception e) {
        Log.e("FetchUrL", "Error in http connection:" + e.toString());
        return null;
    }

    String resultString = result.toString();
    String regex = "(?i)<h1>Unauthorized Access</h1>";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(resultString);
    if (matcher.matches())
        return "Unauthorized";

    Log.i("FetchUrL content: ", result.toString());
    return resultString;

}

From source file:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }/*from   w  ww  .j av a2 s . c o  m*/

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);

    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

static Credentials getCredentials(final String username, final String password, final InetAddress address) {
    int i = username.indexOf("\\"); //$NON-NLS-1$
    if (i > 0 && i < username.length() - 1 && address != null) {
        return new NTCredentials(username.substring(i + 1), password, address.getHostName(),
                username.substring(0, i));
    } else {//from ww w  .j  a v a2s.  co  m
        return new UsernamePasswordCredentials(username, password);
    }
}

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

private HttpClient setupClient(URL url, SampleResult res) {

    Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY
            .get();/*from   w w w  . jav a  2  s.com*/

    final String host = url.getHost();
    final String proxyHost = getProxyHost();
    final int proxyPort = getProxyPortInt();

    boolean useStaticProxy = isStaticProxy(host);
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);

    // Lookup key - must agree with all the values used to create the HttpClient.
    HttpClientKey key = new HttpClientKey(url, (useStaticProxy || useDynamicProxy),
            useDynamicProxy ? proxyHost : PROXY_HOST, useDynamicProxy ? proxyPort : PROXY_PORT,
            useDynamicProxy ? getProxyUser() : PROXY_USER, useDynamicProxy ? getProxyPass() : PROXY_PASS);

    HttpClient httpClient = mapHttpClientPerHttpClientKey.get(key);

    if (httpClient != null && resetSSLContext
            && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) {
        ((AbstractHttpClient) httpClient).clearRequestInterceptors();
        ((AbstractHttpClient) httpClient).clearResponseInterceptors();
        httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) { // One-time init for this client

        HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);

        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = new SystemDefaultDnsResolver();
        }
        ClientConnectionManager connManager = new MeasuringConnectionManager(
                SchemeRegistryFactory.createDefault(), resolver);

        httpClient = new DefaultHttpClient(connManager, clientParams) {
            @Override
            protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count
            }
        };
        if (IDLE_TIMEOUT > 0) {
            ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY);
        }
        ((AbstractHttpClient) httpClient).addResponseInterceptor(new ResponseContentEncoding());
        ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK
        ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER);

        // Override the defualt schemes as necessary
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        if (SLOW_HTTP != null) {
            schemeRegistry.register(SLOW_HTTP);
        }

        if (HTTPS_SCHEME != null) {
            schemeRegistry.register(HTTPS_SCHEME);
        }

        // Set up proxy details
        if (useDynamicProxy) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            String proxyUser = getProxyUser();

            if (proxyUser.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUser, getProxyPass(), localHost, PROXY_DOMAIN));
            }
        } else if (useStaticProxy) {
            HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            if (PROXY_USER.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT),
                        new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN));
            }
        }

        // Bug 52126 - we do our own cookie handling
        clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }

        mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
    }

    MeasuringConnectionManager connectionManager = (MeasuringConnectionManager) httpClient
            .getConnectionManager();
    connectionManager.setSample(res);

    // TODO - should this be done when the client is created?
    // If so, then the details need to be added as part of HttpClientKey
    setConnectionAuthorization(httpClient, url, getAuthManager(), key);

    return httpClient;
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected void setAuthenticationInfo(AbstractHttpClient agent, MessageContext msgCtx) throws AxisFault {
    HTTPAuthenticator authenticator;/* w  w w.  j a v  a 2 s . c  o  m*/
    Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
    if (obj != null) {
        if (obj instanceof HTTPAuthenticator) {
            authenticator = (HTTPAuthenticator) obj;

            String username = authenticator.getUsername();
            String password = authenticator.getPassword();
            String host = authenticator.getHost();
            String domain = authenticator.getDomain();

            int port = authenticator.getPort();
            String realm = authenticator.getRealm();

            /* If retrying is available set it first */
            isAllowedRetry = authenticator.isAllowedRetry();

            Credentials creds;

            // TODO : Set preemptive authentication, but its not recommended in HC 4

            if (host != null) {
                if (domain != null) {
                    /* Credentials for NTLM Authentication */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, host, domain);
                } else {
                    /* Credentials for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                }
                agent.getCredentialsProvider().setCredentials(new AuthScope(host, port, realm), creds);
            } else {
                if (domain != null) {
                    /*
                     * Credentials for NTLM Authentication when host is
                     * ANY_HOST
                     */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
                    agent.getCredentialsProvider()
                            .setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
                } else {
                    /* Credentials only for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                    agent.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), creds);
                }
            }
            /* Customizing the priority Order */
            List schemes = authenticator.getAuthSchemes();
            if (schemes != null && schemes.size() > 0) {
                List authPrefs = new ArrayList(3);
                for (int i = 0; i < schemes.size(); i++) {
                    if (schemes.get(i) instanceof AuthPolicy) {
                        authPrefs.add(schemes.get(i));
                        continue;
                    }
                    String scheme = (String) schemes.get(i);
                    authPrefs.add(authenticator.getAuthPolicyPref(scheme));

                }
                agent.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPrefs);
            }

        } else {
            throw new AxisFault("HttpTransportProperties.Authenticator class cast exception");
        }
    }

}

From source file:com.docuware.dev.Extensions.ServiceConnection.java

static public CompletableFuture<ServiceConnection> createWithWindowsAuthenticationAsync(String serviceUri,
        String userName, String password, String domain, String organization, DWProductTypes licenseType,
        ApacheHttpClientHandler httpClientHandler, String[] userAgent) {
    NTCredentials c = new NTCredentials(userName, password, System.getenv("COMPUTERNAME"), domain);
    return createWithWindowsAuthenticationAsync(serviceUri, c,
            ServiceConnectionLoginData.Create(organization, licenseType, httpClientHandler, userAgent));
}

From source file:org.apache.manifoldcf.crawler.connectors.livelink.LivelinkConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    getSessionParameters();// w  ww. j  a  va 2  s  .  com
    if (hasConnected == false) {
        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // Set up ingest ssl if indicated
        SSLConnectionSocketFactory myFactory = null;
        if (ingestKeystoreManager != null) {
            myFactory = new SSLConnectionSocketFactory(
                    new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(),
                            connectionTimeout),
                    new BrowserCompatHostnameVerifier());
        }

        // Set up authentication to use
        if (ingestNtlmDomain != null) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(ingestNtlmUsername, ingestNtlmPassword, currentHost, ingestNtlmDomain));
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries()
                .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true)
                        .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                        .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                        .setConnectionRequestTimeout(socketTimeout).build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());

        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);

        httpClient = builder.build();

        // System.out.println("Connection server object = "+llServer.toString());

        // Establish the actual connection
        int sanityRetryCount = FAILURE_RETRY_COUNT;
        while (true) {
            GetSessionThread t = new GetSessionThread();
            try {
                t.start();
                t.finishUp();
                hasConnected = true;
                break;
            } catch (InterruptedException e) {
                t.interrupt();
                throw new ManifoldCFException("Interrupted: " + e.getMessage(), e,
                        ManifoldCFException.INTERRUPTED);
            } catch (RuntimeException e2) {
                sanityRetryCount = handleLivelinkRuntimeException(e2, sanityRetryCount, true);
            }
        }
    }
    expirationTime = System.currentTimeMillis() + expirationInterval;
}

From source file:com.docuware.dev.Extensions.ServiceConnection.java

static public ServiceConnection createWithWindowsAuthentication(String serviceUri, String userName,
        String password, String domain, String organization, DWProductTypes licenseType,
        ApacheHttpClientHandler httpClientHandler, String[] userAgent) {
    NTCredentials c = new NTCredentials(userName, password, System.getenv("COMPUTERNAME"), domain);
    try {/*ww w.j  a  v a 2s  .  co  m*/
        return createWithWindowsAuthenticationAsync(serviceUri, c,
                ServiceConnectionLoginData.Create(organization, licenseType, httpClientHandler, userAgent))
                        .get();
    } catch (InterruptedException | ExecutionException ex) {
        throw new RuntimeException(ex.getCause());
    }
}