Skip to content

Commit

Permalink
Using AuthCache for Apache HttpClient to do pre-emptive authentication.
Browse files Browse the repository at this point in the history
  • Loading branch information
sagarsane committed Oct 12, 2015
1 parent a2269d5 commit 8e8e4bf
Showing 1 changed file with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,17 @@ import com.twcable.grabbit.jcr.JcrUtil
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.apache.http.HttpEntity
import org.apache.http.HttpHost
import org.apache.http.HttpResponse
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.AuthCache
import org.apache.http.client.CredentialsProvider
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.protocol.HttpClientContext
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.impl.client.BasicAuthCache
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.sling.jcr.api.SlingRepository
Expand Down Expand Up @@ -108,6 +114,24 @@ class ClientBatchJobExecutionListener implements JobExecutionListener {
client
}

/**
* Gets a new HttpClientContext for the given HttpRequest. The ClientContext sets up preemptive
* authentication using BasicAuthCache
* @param get the HttpGet request
* @return the HttpClientContext for given HttpRequest
*/
private HttpClientContext getHttpClientContext(HttpGet get) {
// Setup preemptive Authentication
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache()
HttpHost host = new HttpHost(get.URI.host, get.URI.port, get.URI.scheme)
authCache.put(host, new BasicScheme())
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create()
context.setAuthCache(authCache)
return context
}

/**
* Makes a Http Get request to the grab path and returns the response
* @param jobParameters that contain information like the path, host, port, etc.
Expand Down Expand Up @@ -135,7 +159,9 @@ class ClientBatchJobExecutionListener implements JobExecutionListener {

//create the get request
HttpGet get = new HttpGet(uriBuilder.build())
HttpResponse response = getHttpClient(username, password).execute(get)
HttpClient client = getHttpClient(username, password)
HttpClientContext context = getHttpClientContext(get)
HttpResponse response = client.execute(get, context)
response
}

Expand Down

0 comments on commit 8e8e4bf

Please sign in to comment.