public HttpConnectionInterceptorException(Throwable cause) { this.initCause(cause); this.error = null; this.reason = null; }
boolean requestCookie(HttpConnectionInterceptorContext context) { return requestCookie(context, sessionURL, sessionRequestBody, sessionRequestMimeType, "application/json", new OnExecuteCallable() { @Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { // If the session did not start, consume the error stream to avoid // leaking connections. Utils.consumeAndCloseStream(connection.getConnection().getErrorStream ()); return false; } } } ); }
/** * Construct a new timeout interceptor with the specified connect and read timeouts. * <P> * Example to create a timeout interceptor with 10 second connect timeout and 5 minute read * timeout. * </P> * <pre> * {@code * new TimeoutCustomizationInterceptor(10, TimeUnit.SECONDS, 5, TimeUnit.MINUTES); * } * </pre> * * @param connectTimeoutValue value of the connect timeout * @param connectTimeoutUnit TimeUnit for the duration of the connect timeout * @param readTimeoutValue value of the read timeout * @param readTimeoutUnit TimeUnit for the duration of the read timeout */ public TimeoutCustomizationInterceptor(long connectTimeoutValue, TimeUnit connectTimeoutUnit, long readTimeoutValue, TimeUnit readTimeoutUnit) { this.connectTimeout = asIntMillis(connectTimeoutValue, connectTimeoutUnit); this.readTimeout = asIntMillis(readTimeoutValue, readTimeoutUnit); }
IamCookieInterceptor cookieInterceptor = new IamCookieInterceptor(this.iamApiKey, this.url.toString()); props.addRequestInterceptors(new IamServerBasicAuthInterceptor( cookieInterceptor.getIamServerUrl(), iamServerClientId, iamServerClientSecret)); CookieInterceptor cookieInterceptor = new CookieInterceptor(username, password, this.url.toString()); props.addRequestInterceptors(new TimeoutCustomizationInterceptor(connectTimeout, connectTimeoutUnit, readTimeout, readTimeoutUnit)); props.addRequestInterceptors(new ProxyAuthInterceptor(proxyUser, proxyPassword)); logger.config("Added proxy auth interceptor"); props.addRequestInterceptors(new SSLCustomizerInterceptor( authenticatedModeSSLSocketFactory ));
private void setAuthInterceptor(String uriHost, String uriPath, String uriProtocol, int uriPort) { if (iamApiKey != null) { URI baseURI = getBaseUri(uriHost, uriPath, uriProtocol, uriPort); IamCookieInterceptor ici = new IamCookieInterceptor(iamApiKey, baseURI.toString()); requestInterceptors.add(ici); responseInterceptors.add(ici); } else if (this.username != null && this.password != null) { URI baseURI = getBaseUri(uriHost, uriPath, uriProtocol, uriPort); CookieInterceptor ci = new CookieInterceptor(this.username, this.password, baseURI .toString()); requestInterceptors.add(ci); responseInterceptors.add(ci); } }
private CookieInterceptor buildCookieInterceptor() { if (username != null && password != null) { String path = rootUri.getRawPath() == null ? "" : rootUri.getRawPath(); if (path.length() > 0) { int index = path.lastIndexOf("/"); if (index == path.length() - 1) { // we need to go back one path = path.substring(0, index); index = path.lastIndexOf("/"); } path = path.substring(0, index); } URI baseURI; try { baseURI = new URI(rootUri.getScheme(), null, rootUri.getHost(), rootUri.getPort() , path, null, null); Logger.getLogger(this.getClass().getCanonicalName()).info(String.format(Locale.ENGLISH, "Cookie info: %s", baseURI)); } catch (URISyntaxException e) { throw new RuntimeException(e); } return new CookieInterceptor(username, password, baseURI.toString()); } return null; }
public CouchConfig(URI rootUri, List<HttpConnectionRequestInterceptor> requestInterceptors, List<HttpConnectionResponseInterceptor> responseInterceptors, String username, String password) { this.rootUri = rootUri; this.requestInterceptors = requestInterceptors; this.responseInterceptors = responseInterceptors; this.username = username; this.password = password; if (TestOptions.COUCH_IAM_API_KEY != null) { int slash = this.rootUri.toString().lastIndexOf("/"); String root = this.rootUri.toString().substring(0, slash); IamCookieInterceptor ici = new IamCookieInterceptor(TestOptions.COUCH_IAM_API_KEY, root); this.requestInterceptors.add(ici); this.responseInterceptors.add(ici); } }
HttpConnectionInterceptorException(errorString); boolean success = requestCookie(context); if (success) { storeCookiesFromResponse(connection);
/** * Assert that the User-Agent header is of the expected form. */ @Test public void testUserAgentHeaderString() throws Exception { // This doesn't read the a properties file, since the tests do not run from the published // jars. String userAgentHeader = new UserAgentInterceptor(UserAgentInterceptor.class .getClassLoader(), "META-INF/com.cloudant.client.properties").getUserAgent(); assertTrue(userAgentHeader.matches(userAgentUnknownRegex), "The value of the User-Agent " + "header: " + userAgentHeader + " should match the " + "format: " + userAgentFormat); }
private String getBearerToken(HttpConnectionInterceptorContext context) { final AtomicReference<String> iamTokenResponse = new AtomicReference<String>(); boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody, "application/x-www-form-urlencoded", "application/json", new StoreBearerCallable(iamTokenResponse)); if (result) { return iamTokenResponse.get(); } else { return null; } }
String token = getBearerToken(context); if (token == null) { return false; return super.requestCookie(context);
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { // Check if this interceptor is valid before attempting any kind of renewal try { if (shouldAttemptCookieRequest.get()) { HttpURLConnection connection = context.connection.getConnection(); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { boolean success = requestCookie(context); if (success) { context.replayRequest = true; // Consume the error stream to avoid leaking connections Utils.consumeAndCloseStream(connection.getErrorStream()); logger.log(Level.FINEST, "Consumed error response"); } else { context.replayRequest = false; // Don't replay shouldAttemptCookieRequest.set(false); // Set the flag to stop trying } } else { // Store any cookies provided on the response storeCookiesFromResponse(connection); } } } catch (IOException e) { logger.log(Level.SEVERE, "Error reading response code or body from request", e); } return context; }
if (!requestCookie(context)) { if (cookies != null && !cookies.isEmpty()) { connection.setRequestProperty(requestCookieHeader.getKey(), listToSemicolonSeparatedString(cookies)); } else { logger.finest("No cookie values to set.");
return new SSLCustomizerInterceptor(new TlsOnlySslSocketFactory(s));
String prefix = UserAgentInterceptor.loadUA(loader, filepath); String runtimeVersion = System.getProperty("java.version", "Unknown"); if (runtimeVersion.equals("0")){
@Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { // If the session did not start, consume the error stream to avoid // leaking connections. Utils.consumeAndCloseStream(connection.getConnection().getErrorStream ()); return false; } } }
return onResponseOk.call(connection); } else {
@BeforeEach public void setupSessionInterceptor(boolean okUsable, String sessionPath) { this.mockWebServer = mockWebServerExt.get(); this.mockIamServer = mockIamServerExt.get(); String baseUrl = mockWebServer.url("").toString(); if (sessionPath.equals("/_session")) { CookieInterceptor ci = new CookieInterceptor("user", "pass", baseUrl); rqInterceptor = ci; rpInterceptor = ci; } else if (sessionPath.equals("/_iam_session")) { // Set the endpoint value before each test iamSystemPropertyMock.setMockIamTokenEndpointUrl(mockIamServer.url("/identity/token") .toString()); IamCookieInterceptor ici = new IamCookieInterceptor("apikey", baseUrl); rqInterceptor = ici; rpInterceptor = ici; } else { fail("Invalid sessionPath " + sessionPath); } }
CookieInterceptor interceptor = new CookieInterceptor(TestOptions.COUCH_USERNAME, TestOptions.COUCH_PASSWORD, getCouchConfig("httptest" + System
@Test public void testUserAgentHeaderStringFromFile() throws Exception { // This doesn't read the a properties file, since the tests do not run from the published // jars. // Point to the built classes, it's a bit awkward but we need to load the class cleanly File f = new File("../cloudant-http/build/classes/main/"); String userAgentHeader = new UserAgentInterceptor(new URLClassLoader(new URL[]{f.toURI() .toURL()}) { @Override public InputStream getResourceAsStream(String name) { if (name.equals("META-INF/com.cloudant.client.properties")) { try { return new ByteArrayInputStream(("user.agent.name=java-cloudant\nuser" + ".agent.version=1.6.1").getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return super.getResourceAsStream(name); } }, "META-INF/com.cloudant.client.properties").getUserAgent(); assertTrue(userAgentHeader.matches(userAgentRegex), "The value of the User-Agent header: " + "" + userAgentHeader + " should match the " + "format: " + userAgentFormat); }