Example usage for org.apache.http.impl.client BasicCredentialsProvider setCredentials

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider setCredentials.

Prototype

public void setCredentials(final AuthScope authscope, final Credentials credentials) 

Source Link

Usage

From source file:org.sonatype.nexus.plugin.deploy.ZapperImpl.java

@Override
public void deployDirectory(final ZapperRequest zapperRequest) throws IOException {
    try {//from   w  w  w . j  a va2 s  . com
        HttpHost proxyServer = null;
        BasicCredentialsProvider credentialsProvider = null;
        if (!StringUtils.isBlank(zapperRequest.getProxyProtocol())) {
            proxyServer = new HttpHost(zapperRequest.getProxyHost(), zapperRequest.getProxyPort(),
                    zapperRequest.getProxyProtocol());

            if (!StringUtils.isBlank(zapperRequest.getProxyUsername())) {
                UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(
                        zapperRequest.getProxyUsername(), zapperRequest.getProxyPassword());

                credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxyServer.getHostName(),
                        proxyServer.getPort(), AuthScope.ANY_REALM, proxyServer.getSchemeName()),
                        proxyCredentials);
            }
        }

        if (!StringUtils.isBlank(zapperRequest.getRemoteUsername())) {
            UsernamePasswordCredentials remoteCredentials = new UsernamePasswordCredentials(
                    zapperRequest.getRemoteUsername(), zapperRequest.getRemotePassword());

            if (credentialsProvider == null) {
                credentialsProvider = new BasicCredentialsProvider();
            }

            credentialsProvider.setCredentials(AuthScope.ANY, remoteCredentials);
        }

        final Parameters parameters = ParametersBuilder.defaults().build();
        final Hc4ClientBuilder clientBuilder = new Hc4ClientBuilder(parameters, zapperRequest.getRemoteUrl());
        if (credentialsProvider != null) {
            clientBuilder.withRealm(credentialsProvider);
        }
        if (proxyServer != null) {
            clientBuilder.withProxy(proxyServer);
        }
        final Client client = clientBuilder.build();
        final IOSourceListable deployables = new DirectoryIOSource(zapperRequest.getStageRepository());

        try {
            client.upload(deployables);
        } finally {
            client.close();
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException("Unable to deploy!", e);
    }
}

From source file:com.servoy.extensions.plugins.http.BaseRequest.java

private Response executeRequest(String userName, String password, String workstation, String domain,
        boolean windowsAuthentication) throws Exception {
    HttpEntity entity = buildEntity();/*from www. j a v a 2  s  .  com*/
    if (entity != null)
        ((HttpEntityEnclosingRequestBase) method).setEntity(entity);

    Iterator<String> it = headers.keySet().iterator();
    while (it.hasNext()) {
        String name = it.next();
        String[] values = headers.get(name);
        for (String value : values) {
            method.addHeader(name, value);
        }
    }

    if (!Utils.stringIsEmpty(userName)) {
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        URL _url = HttpProvider.createURLFromString(url, access);
        Credentials cred = null;
        if (windowsAuthentication) {
            if (context == null) {
                context = new BasicHttpContext();
            }
            cred = new NTCredentials(userName, password, workstation, domain);
        } else {
            cred = new UsernamePasswordCredentials(userName, password);
        }
        bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()), cred);
        client.setCredentialsProvider(bcp);
    }

    return new Response(client.execute(method, context));
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClient.java

private HttpContext httpContext() {
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    if (isNotBlank(this.username) && this.password != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        HttpHost httpHost = HttpHost.create(this.rootConfluenceUrl);
        AuthScope authScope = new AuthScope(httpHost);
        basicCredentialsProvider.setCredentials(authScope, credentials);

        BasicAuthCache basicAuthCache = new BasicAuthCache();
        basicAuthCache.put(httpHost, new BasicScheme());

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(basicCredentialsProvider);
        httpClientContext.setAuthCache(basicAuthCache);

        return httpClientContext;
    } else {//ww  w.  j  a v  a  2  s.c o m
        return null;
    }
}

From source file:com.srotya.collectd.storm.StormNimbusMetrics.java

@Override
public int config(OConfigItem config) {
    nimbusAddresses = new ArrayList<>();
    String jaasPath = "jaas.conf";
    List<OConfigItem> children = config.getChildren();
    for (OConfigItem child : children) {
        switch (child.getKey().toLowerCase()) {
        case "address":
            for (OConfigValue nimbus : child.getValues()) {
                try {
                    new URI(nimbus.toString());
                } catch (Exception e) {
                    Collectd.logError("Bad URI " + nimbus + " for Nimbus, error:" + e.getMessage());
                    return -1;
                }//w w w . j  a  v a  2s . c  o  m
                nimbusAddresses.add(nimbus.getString());
            }
            break;
        case "kerberos":
            kerberos = child.getValues().get(0).getBoolean();
            break;
        case "jaas":
            jaasPath = child.getValues().get(0).getString();
            break;
        }
    }
    Collectd.logInfo("Storm Nimbus Plugin: using following Nimbuses:" + nimbusAddresses);
    Collectd.logInfo("Storm Nimbus Plugin: using kerberos:" + kerberos);

    builder = HttpClientBuilder.create();
    context = HttpClientContext.create();
    if (kerberos) {
        System.setProperty("java.security.auth.login.config", jaasPath);
        System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "true");

        login();

        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // This may seem odd, but specifying 'null' as principal tells java
        // to
        // use the logged in user's credentials
        Credentials useJaasCreds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };
        credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds);
        context.setCredentialsProvider(credentialsProvider);

    } else {
        subject = Subject.getSubject(AccessController.getContext());
    }
    return 0;
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build/*from w  ww.  j av  a  2s  .co  m*/
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * @param clientName/*from  www.j av  a  2  s  .  c  o  m*/
 * @param url
 * @param fileName
 * @param filePath
 * @param username
 * @param password
 * @return
 */
private boolean put(String clientName, String url, String fileName, String filePath, String username,
        String password) {
    if ("".equals(clientName.trim()))
        return false;

    int status = 0;
    try {
        URL _url = createURLFromString(url);
        HttpPut method = new HttpPut(url + "/" + fileName);
        DefaultHttpClient client = getOrCreateHTTPclient(clientName, url);
        File file = new File(filePath);

        if (username != null && !"".equals(username.trim())) {
            BasicCredentialsProvider bcp = new BasicCredentialsProvider();
            bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()),
                    new UsernamePasswordCredentials(username, password));
            client.setCredentialsProvider(bcp);
        }

        if (file == null || !file.exists()) {
            return false;
        }
        method.setEntity(new FileEntity(file, "binary/octet-stream"));
        HttpResponse res = client.execute(method);
        status = res.getStatusLine().getStatusCode();
    } catch (IOException e) {
        return false;
    }

    return (status == HttpStatus.SC_OK);
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * @param url/*from w w w . j a v  a 2s.  co  m*/
 * @param httpClientName
 * @param username
 * @param password
 * @return
 */
private String getPageData(String url, String httpClientName, String username, String password) {
    try {
        DefaultHttpClient client = getOrCreateHTTPclient(httpClientName, url);
        HttpGet get = new HttpGet(url);
        HttpResponse res = client.execute(get); // you can get the status from here... (return code)
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        if (username != null) {
            URL _url = createURLFromString(url);
            bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()),
                    new UsernamePasswordCredentials(username, password));
            client.setCredentialsProvider(bcp);
        }
        lastPageEncoding = EntityUtils.getContentCharSet(res.getEntity());
        return EntityUtils.toString(res.getEntity());
    } catch (Exception e) {
        Debug.error(e);
        return "";//$NON-NLS-1$
    }
}

From source file:com.unboundid.scim.tools.SCIMQueryRate.java

/**
 * Performs the actual processing for this tool.  In this case, it gets a
 * connection to the directory server and uses it to perform the requested
 * searches./*from w  w  w  .j a v a 2 s  .c o  m*/
 *
 * @return  The result code for the processing that was performed.
 */
@Override()
public ResultCode doToolProcessing() {
    //Initalize the Debugger
    Debug.setEnabled(true);
    Debug.getLogger().addHandler(new ConsoleHandler());
    Debug.getLogger().setUseParentHandlers(false);

    // Determine the random seed to use.
    final Long seed;
    if (randomSeed.isPresent()) {
        seed = Long.valueOf(randomSeed.getValue());
    } else {
        seed = null;
    }

    // Create a value pattern for the filter.
    final ValuePattern filterPattern;
    boolean isQuery = true;
    if (filter.isPresent()) {
        try {
            filterPattern = new ValuePattern(filter.getValue(), seed);
        } catch (ParseException pe) {
            Debug.debugException(pe);
            err(ERR_QUERY_TOOL_BAD_FILTER_PATTERN.get(pe.getMessage()));
            return ResultCode.PARAM_ERROR;
        }
    } else if (resourceId.isPresent()) {
        isQuery = false;
        try {
            filterPattern = new ValuePattern(resourceId.getValue());
        } catch (ParseException pe) {
            Debug.debugException(pe);
            err(ERR_QUERY_TOOL_BAD_RESOURCE_ID_PATTERN.get(pe.getMessage()));
            return ResultCode.PARAM_ERROR;
        }
    } else {
        filterPattern = null;
    }

    // Get the attributes to return.
    final String[] attrs;
    if (attributes.isPresent()) {
        final List<String> attrList = attributes.getValues();
        attrs = new String[attrList.size()];
        attrList.toArray(attrs);
    } else {
        attrs = NO_STRINGS;
    }

    // If the --ratePerSecond option was specified, then limit the rate
    // accordingly.
    FixedRateBarrier fixedRateBarrier = null;
    if (ratePerSecond.isPresent()) {
        final int intervalSeconds = collectionInterval.getValue();
        final int ratePerInterval = ratePerSecond.getValue() * intervalSeconds;

        fixedRateBarrier = new FixedRateBarrier(1000L * intervalSeconds, ratePerInterval);
    }

    // Determine whether to include timestamps in the output and if so what
    // format should be used for them.
    final boolean includeTimestamp;
    final String timeFormat;
    if (timestampFormat.getValue().equalsIgnoreCase("with-date")) {
        includeTimestamp = true;
        timeFormat = "dd/MM/yyyy HH:mm:ss";
    } else if (timestampFormat.getValue().equalsIgnoreCase("without-date")) {
        includeTimestamp = true;
        timeFormat = "HH:mm:ss";
    } else {
        includeTimestamp = false;
        timeFormat = null;
    }

    // Determine whether any warm-up intervals should be run.
    final long totalIntervals;
    final boolean warmUp;
    int remainingWarmUpIntervals = warmUpIntervals.getValue();
    if (remainingWarmUpIntervals > 0) {
        warmUp = true;
        totalIntervals = 0L + numIntervals.getValue() + remainingWarmUpIntervals;
    } else {
        warmUp = true;
        totalIntervals = 0L + numIntervals.getValue();
    }

    // Create the table that will be used to format the output.
    final OutputFormat outputFormat;
    if (csvFormat.isPresent()) {
        outputFormat = OutputFormat.CSV;
    } else {
        outputFormat = OutputFormat.COLUMNS;
    }

    final ColumnFormatter formatter = new ColumnFormatter(includeTimestamp, timeFormat, outputFormat, " ",
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Queries/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Avg Dur ms"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Resources/Query"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Errors/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Overall", "Queries/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Overall", "Avg Dur ms"));

    // Create values to use for statistics collection.
    final AtomicLong queryCounter = new AtomicLong(0L);
    final AtomicLong resourceCounter = new AtomicLong(0L);
    final AtomicLong errorCounter = new AtomicLong(0L);
    final AtomicLong queryDurations = new AtomicLong(0L);

    // Determine the length of each interval in milliseconds.
    final long intervalMillis = 1000L * collectionInterval.getValue();

    // We will use Apache's HttpClient library for this tool.
    SSLUtil sslUtil;
    try {
        sslUtil = createSSLUtil();
    } catch (LDAPException e) {
        debugException(e);
        err(e.getMessage());
        return e.getResultCode();
    }

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    final String schemeName;
    if (sslUtil != null) {
        try {
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslUtil.createSSLContext("TLS"), new NoopHostnameVerifier());
            schemeName = "https";
            registryBuilder.register(schemeName, sslConnectionSocketFactory);
        } catch (GeneralSecurityException e) {
            debugException(e);
            err(ERR_SCIM_TOOL_CANNOT_CREATE_SSL_CONTEXT.get(getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
    } else {
        schemeName = "http";
        registryBuilder.register(schemeName, new PlainConnectionSocketFactory());
    }
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder.build();

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
            .setExpectContinueEnabled(true).build();

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(30000).setSoReuseAddress(true).build();

    final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    mgr.setMaxTotal(numThreads.getValue());
    mgr.setDefaultMaxPerRoute(numThreads.getValue());
    mgr.setDefaultSocketConfig(socketConfig);
    mgr.setValidateAfterInactivity(-1);

    ClientConfig jerseyConfig = new ClientConfig();

    jerseyConfig.property(ApacheClientProperties.CONNECTION_MANAGER, mgr);
    jerseyConfig.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
    ApacheConnectorProvider connectorProvider = new ApacheConnectorProvider();
    jerseyConfig.connectorProvider(connectorProvider);

    if (authID.isPresent()) {
        try {
            final String password;
            if (authPassword.isPresent()) {
                password = authPassword.getValue();
            } else if (authPasswordFile.isPresent()) {
                password = authPasswordFile.getNonBlankFileLines().get(0);
            } else {
                password = null;
            }

            BasicCredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(host.getValue(), port.getValue()),
                    new UsernamePasswordCredentials(authID.getValue(), password));

            jerseyConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, provider);
            jerseyConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
        } catch (IOException e) {
            Debug.debugException(e);
            err(ERR_QUERY_TOOL_SET_BASIC_AUTH.get(e.getMessage()));
            return ResultCode.LOCAL_ERROR;
        }
    } else if (bearerToken.isPresent()) {
        jerseyConfig.register(new ClientRequestFilter() {
            public void filter(final ClientRequestContext clientRequestContext) throws IOException {
                try {
                    clientRequestContext.getHeaders().add("Authorization", "Bearer " + bearerToken.getValue());
                } catch (Exception ex) {
                    throw new RuntimeException("Unable to add authorization handler", ex);
                }
            }
        });
    }

    // Create the SCIM client to use for the queries.
    final URI uri;
    try {
        final String path;
        if (contextPath.getValue().startsWith("/")) {
            path = contextPath.getValue();
        } else {
            path = "/" + contextPath.getValue();
        }
        uri = new URI(schemeName, null, host.getValue(), port.getValue(), path, null, null);
    } catch (URISyntaxException e) {
        Debug.debugException(e);
        err(ERR_QUERY_TOOL_CANNOT_CREATE_URL.get(e.getMessage()));
        return ResultCode.OTHER;
    }
    final SCIMService service = new SCIMService(uri, jerseyConfig);

    if (xmlFormat.isPresent()) {
        service.setContentType(MediaType.APPLICATION_XML_TYPE);
        service.setAcceptType(MediaType.APPLICATION_XML_TYPE);
    }

    // Retrieve the resource schema.
    final ResourceDescriptor resourceDescriptor;
    try {
        resourceDescriptor = service.getResourceDescriptor(resourceName.getValue(), null);
        if (resourceDescriptor == null) {
            throw new ResourceNotFoundException(
                    "Resource " + resourceName.getValue() + " is not defined by the service provider");
        }
    } catch (SCIMException e) {
        Debug.debugException(e);
        err(ERR_QUERY_TOOL_RETRIEVE_RESOURCE_SCHEMA.get(e.getMessage()));
        return ResultCode.OTHER;
    }

    final SCIMEndpoint<? extends BaseResource> endpoint = service.getEndpoint(resourceDescriptor,
            BaseResource.BASE_RESOURCE_FACTORY);

    // Create the threads to use for the searches.
    final CyclicBarrier barrier = new CyclicBarrier(numThreads.getValue() + 1);
    final QueryRateThread[] threads = new QueryRateThread[numThreads.getValue()];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new QueryRateThread(i, isQuery, endpoint, filterPattern, attrs, barrier, queryCounter,
                resourceCounter, queryDurations, errorCounter, fixedRateBarrier);
        threads[i].start();
    }

    // Display the table header.
    for (final String headerLine : formatter.getHeaderLines(true)) {
        out(headerLine);
    }

    // Indicate that the threads can start running.
    try {
        barrier.await();
    } catch (Exception e) {
        Debug.debugException(e);
    }
    long overallStartTime = System.nanoTime();
    long nextIntervalStartTime = System.currentTimeMillis() + intervalMillis;

    boolean setOverallStartTime = false;
    long lastDuration = 0L;
    long lastNumEntries = 0L;
    long lastNumErrors = 0L;
    long lastNumSearches = 0L;
    long lastEndTime = System.nanoTime();
    for (long i = 0; i < totalIntervals; i++) {
        final long startTimeMillis = System.currentTimeMillis();
        final long sleepTimeMillis = nextIntervalStartTime - startTimeMillis;
        nextIntervalStartTime += intervalMillis;
        try {
            if (sleepTimeMillis > 0) {
                Thread.sleep(sleepTimeMillis);
            }
        } catch (Exception e) {
            Debug.debugException(e);
        }

        final long endTime = System.nanoTime();
        final long intervalDuration = endTime - lastEndTime;

        final long numSearches;
        final long numEntries;
        final long numErrors;
        final long totalDuration;
        if (warmUp && (remainingWarmUpIntervals > 0)) {
            numSearches = queryCounter.getAndSet(0L);
            numEntries = resourceCounter.getAndSet(0L);
            numErrors = errorCounter.getAndSet(0L);
            totalDuration = queryDurations.getAndSet(0L);
        } else {
            numSearches = queryCounter.get();
            numEntries = resourceCounter.get();
            numErrors = errorCounter.get();
            totalDuration = queryDurations.get();
        }

        final long recentNumSearches = numSearches - lastNumSearches;
        final long recentNumEntries = numEntries - lastNumEntries;
        final long recentNumErrors = numErrors - lastNumErrors;
        final long recentDuration = totalDuration - lastDuration;

        final double numSeconds = intervalDuration / 1000000000.0d;
        final double recentSearchRate = recentNumSearches / numSeconds;
        final double recentErrorRate = recentNumErrors / numSeconds;

        final double recentAvgDuration;
        final double recentEntriesPerSearch;
        if (recentNumSearches > 0L) {
            recentEntriesPerSearch = 1.0d * recentNumEntries / recentNumSearches;
            recentAvgDuration = 1.0d * recentDuration / recentNumSearches / 1000000;
        } else {
            recentEntriesPerSearch = 0.0d;
            recentAvgDuration = 0.0d;
        }

        if (warmUp && (remainingWarmUpIntervals > 0)) {
            out(formatter.formatRow(recentSearchRate, recentAvgDuration, recentEntriesPerSearch,
                    recentErrorRate, "warming up", "warming up"));

            remainingWarmUpIntervals--;
            if (remainingWarmUpIntervals == 0) {
                out(INFO_QUERY_TOOL_WARM_UP_COMPLETED.get());
                setOverallStartTime = true;
            }
        } else {
            if (setOverallStartTime) {
                overallStartTime = lastEndTime;
                setOverallStartTime = false;
            }

            final double numOverallSeconds = (endTime - overallStartTime) / 1000000000.0d;
            final double overallSearchRate = numSearches / numOverallSeconds;

            final double overallAvgDuration;
            if (numSearches > 0L) {
                overallAvgDuration = 1.0d * totalDuration / numSearches / 1000000;
            } else {
                overallAvgDuration = 0.0d;
            }

            out(formatter.formatRow(recentSearchRate, recentAvgDuration, recentEntriesPerSearch,
                    recentErrorRate, overallSearchRate, overallAvgDuration));

            lastNumSearches = numSearches;
            lastNumEntries = numEntries;
            lastNumErrors = numErrors;
            lastDuration = totalDuration;
        }

        lastEndTime = endTime;
    }

    // Stop all of the threads.
    ResultCode resultCode = ResultCode.SUCCESS;
    for (final QueryRateThread t : threads) {
        t.signalShutdown();
    }

    // Interrupt any blocked threads after a grace period.
    final WakeableSleeper sleeper = new WakeableSleeper();
    sleeper.sleep(1000);
    mgr.shutdown();

    for (final QueryRateThread t : threads) {
        final ResultCode r = t.waitForShutdown();
        if (resultCode == ResultCode.SUCCESS) {
            resultCode = r;
        }
    }

    return resultCode;
}

From source file:org.apache.directory.fortress.core.rest.RestUtils.java

private CredentialsProvider getCredentialProvider(String uid, String password) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(httpHost, Integer.valueOf(httpPort)),
            new UsernamePasswordCredentials(uid == null ? httpUid : uid, password == null ? httpPw : password));
    return credentialsProvider;
}