use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.
the class CloudantClientTests method testBasicAuth.
/**
* Test that adding the Basic Authentication interceptor to CloudantClient works.
*/
@Test
@RequiresCloudant
public void testBasicAuth() throws IOException {
BasicAuthInterceptor interceptor = new BasicAuthInterceptor(CloudantClientHelper.COUCH_USERNAME + ":" + CloudantClientHelper.COUCH_PASSWORD);
CloudantClient client = ClientBuilder.account(CloudantClientHelper.COUCH_USERNAME).interceptors(interceptor).build();
// Test passes if there are no exceptions
client.getAllDbs();
}
use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.
the class CloudantClientTests method testBasicAuthFromCredentials.
/**
* Test that configuring the Basic Authentication interceptor from credentials and adding to
* the CloudantClient works.
*/
@Test
public void testBasicAuthFromCredentials() throws Exception {
BasicAuthInterceptor interceptor = BasicAuthInterceptor.createFromCredentials("username", "password");
// send back a mock OK 200
server.enqueue(new MockResponse());
CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(server).interceptors(interceptor).build();
client.getAllDbs();
// expected 'username:password'
assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", server.takeRequest().getHeader("Authorization"));
}
use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.
the class HttpConnection method execute.
/**
* <p>
* Execute request without returning data from server.
* </p>
* <p>
* Call {@code responseAsString}, {@code responseAsBytes}, or {@code responseAsInputStream}
* after {@code execute} if the response body is required.
* </p>
* <P>
* Note if the URL contains user information it will be encoded in a BasicAuth header.
* </P>
*
* @return An {@link HttpConnection} which can be used to obtain the response body
* @throws IOException if there was a problem writing data to the server
*/
public HttpConnection execute() throws IOException {
boolean retry = true;
while (retry && numberOfRetries-- > 0) {
connection = connectionFactory.openConnection(url);
if (url.getUserInfo() != null) {
// Insert at position 0 in case another interceptor wants to overwrite the BasicAuth
requestInterceptors.add(0, new BasicAuthInterceptor(url.getUserInfo()));
}
// always read the result, so we can retrieve the HTTP response code
connection.setDoInput(true);
connection.setRequestMethod(requestMethod);
if (contentType != null) {
connection.setRequestProperty("Content-type", contentType);
}
// context.connection.getConnection().setChunkedStreamingMode(16384);
if (input != null) {
connection.setDoOutput(true);
if (inputLength != -1) {
// TODO Remove this cast to int when the minimum supported level is 1.7.
// On 1.7 upwards this method takes a long, otherwise int.
connection.setFixedLengthStreamingMode((int) this.inputLength);
} else {
// Use 0 for the default size
connection.setChunkedStreamingMode(0);
// Note that CouchDB does not currently work for a chunked multipart stream, see
// https://issues.apache.org/jira/browse/COUCHDB-1403. Cases that use
// multipart need to provide the content length until that is fixed.
}
}
currentContext = (currentContext == null) ? new HttpConnectionInterceptorContext(this) : new HttpConnectionInterceptorContext(this, currentContext.interceptorStates);
for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) {
currentContext = requestInterceptor.interceptRequest(currentContext);
}
// to the properties map
for (Map.Entry<String, String> property : requestProperties.entrySet()) {
connection.setRequestProperty(property.getKey(), property.getValue());
}
// Log the request
if (requestIsLoggable && logger.isLoggable(Level.FINE)) {
logger.fine(String.format("%s request%s", getLogRequestIdentifier(), (connection.usingProxy() ? " via proxy" : "")));
}
// Log the request headers
if (requestIsLoggable && logger.isLoggable(Level.FINER)) {
logger.finer(String.format("%s request headers %s", getLogRequestIdentifier(), connection.getRequestProperties()));
}
if (input != null) {
InputStream is = input.getInputStream();
OutputStream os = connection.getOutputStream();
try {
// The buffer size used for writing to this output stream has an impact on the
// HTTP chunk size, so we make it a pretty large size to avoid limiting the
// size
// of those chunks (although this appears in turn to set the chunk sizes).
IOUtils.copyLarge(is, os, new byte[16 * 1024]);
os.flush();
} finally {
Utils.close(is);
Utils.close(os);
}
}
// Log the response
if (requestIsLoggable && logger.isLoggable(Level.FINE)) {
logger.fine(String.format("%s response %s %s", getLogRequestIdentifier(), connection.getResponseCode(), connection.getResponseMessage()));
}
// Log the response headers
if (requestIsLoggable && logger.isLoggable(Level.FINER)) {
logger.finer(String.format("%s response headers %s", getLogRequestIdentifier(), connection.getHeaderFields()));
}
for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) {
try {
currentContext = responseInterceptor.interceptResponse(currentContext);
} catch (HttpConnectionInterceptorException e) {
// Sadly the current interceptor API doesn't allow an IOException to be thrown
// so to avoid swallowing them the interceptors need to wrap them in the runtime
// HttpConnectionInterceptorException and we can then unwrap them here.
Throwable cause = e.getCause();
if (cause != null && cause instanceof IOException) {
throw (IOException) cause;
} else {
throw e;
}
}
}
// retry flag is set from the final step in the response interceptRequest pipeline
retry = currentContext.replayRequest;
// makes the connection eligible for re-use.
if (retry && numberOfRetries > 0) {
Utils.consumeAndCloseStream(connection.getErrorStream());
}
if (numberOfRetries == 0) {
logger.info("Maximum number of retries reached");
}
}
// return ourselves to allow method chaining
return this;
}
use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.
the class HttpTest method testBasicAuth.
/**
* Test that adding the Basic Authentication interceptor to HttpConnection
* will complete with a response code of 200. The response input stream
* is expected to hold the newly created document's id and rev.
*/
@TestTemplate
@RequiresCloudant
public void testBasicAuth() throws IOException {
BasicAuthInterceptor interceptor = new BasicAuthInterceptor(CloudantClientHelper.COUCH_USERNAME + ":" + CloudantClientHelper.COUCH_PASSWORD);
HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json");
conn.requestInterceptors.add(interceptor);
ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
// nothing read from stream
assertEquals(data.getBytes().length, bis.available());
conn.setRequestBody(bis);
HttpConnection responseConn = conn.execute();
// stream was read to end
assertEquals(0, bis.available());
assertEquals(2, responseConn.getConnection().getResponseCode() / 100);
// check the json
Gson gson = new Gson();
InputStream is = responseConn.responseAsInputStream();
try {
JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class);
assertTrue(response.has("ok"));
assertTrue(response.get("ok").getAsBoolean());
assertTrue(response.has("id"));
assertTrue(response.has("rev"));
} finally {
is.close();
}
}
Aggregations