use of okhttp3.Connection in project pinpoint by naver.
the class MethodInvocationHandlerInterceptor method createTrace.
/**
* Creates the trace.
*
* @param target the target
* @param args the args
* @return the trace
*/
private Trace createTrace(final Object target, final Object[] args) {
final Method methodInvoked = (Method) args[2];
final StringBuilder methodNameBuilder = new StringBuilder();
if (methodInvoked != null) {
try {
final Class<?> declaringClass = methodInvoked.getDeclaringClass();
if (declaringClass != null) {
methodNameBuilder.append(declaringClass.getCanonicalName());
methodNameBuilder.append(".");
}
methodNameBuilder.append(methodInvoked.getName());
} catch (final Exception exception) {
logger.error("An error occurred while fetching method details", exception);
}
}
final Trace trace = traceContext.newTraceObject();
final Connection connection = RemotingContext.getConnection();
final String remoteAddress = JbossUtility.fetchRemoteAddress(connection);
if (trace.canSampled()) {
final SpanRecorder recorder = trace.getSpanRecorder();
recordRootSpan(recorder, methodNameBuilder.toString(), remoteAddress);
if (isDebug) {
logger.debug("Trace sampling is true, Recording trace. methodInvoked:{}, remoteAddress:{}", methodNameBuilder.toString(), remoteAddress);
}
} else {
if (isDebug) {
logger.debug("Trace sampling is false, Skip recording trace. methodInvoked:{}, remoteAddress:{}", methodNameBuilder.toString(), remoteAddress);
}
}
return trace;
}
use of okhttp3.Connection in project mosby by sockeqwe.
the class HomePresenterTest method loadingFirstPageAndNextPageAndFailPullToRefresh.
@Test
public void loadingFirstPageAndNextPageAndFailPullToRefresh() throws IOException {
//
// Prepare mock server to deliver mock response on incoming http request
//
List<Product> mockProductsFirstPage = Arrays.asList(new Product(1, "image", "name", "category1", "description", 21.9), new Product(2, "image", "name", "category1", "description", 21.9), new Product(3, "image", "name", "category1", "description", 21.9), new Product(4, "image", "name", "category1", "description", 21.9), new Product(5, "image", "name", "category1", "description", 21.9));
List<Product> mockProductsNextPage = Arrays.asList(new Product(6, "image", "name", "category2", "description", 21.9), new Product(7, "image", "name", "category2", "description", 21.9), new Product(8, "image", "name", "category2", "description", 21.9), new Product(9, "image", "name", "category2", "description", 21.9));
List<Product> mockProductsPullToRefresh = Arrays.asList(new Product(10, "image", "name", "category3", "description", 21.9), new Product(11, "image", "name", "category3", "description", 21.9), new Product(12, "image", "name", "category3", "description", 21.9));
mockWebServer.enqueue(new MockResponse().setBody(adapter.toJson(mockProductsFirstPage)));
mockWebServer.enqueue(new MockResponse().setBody(adapter.toJson(mockProductsNextPage)));
mockWebServer.enqueue(new MockResponse().setBody(adapter.toJson(mockProductsPullToRefresh)));
//
// init the robot to drive to View which triggers intents on the presenter
//
HomePresenter presenter = // In a real app you could use dagger or instantiate the Presenter manually like new HomePresenter(...)
new DependencyInjection().newHomePresenter();
HomeViewRobot robot = new HomeViewRobot(presenter);
//
// We are ready, so let's start: fire intents
//
robot.fireLoadFirstPageIntent();
//
// we expect that 2 view.render() events happened with the following HomeViewState:
// 1. show loading indicator
// 2. show the items with the first page
//
List<FeedItem> expectedDataAfterFristPage = Arrays.asList(new SectionHeader("category1"), mockProductsFirstPage.get(0), mockProductsFirstPage.get(1), mockProductsFirstPage.get(2), new AdditionalItemsLoadable(2, "category1", false, null));
HomeViewState loadingFirstPage = new HomeViewState.Builder().firstPageLoading(true).build();
HomeViewState firstPage = new HomeViewState.Builder().data(expectedDataAfterFristPage).build();
// Check if as expected
robot.assertViewStateRendered(loadingFirstPage, firstPage);
//
// Fire next page intent
//
robot.fireLoadNextPageIntent();
//
// we expect that 4 view.render() events happened with the following HomeViewState:
// 1. show loading indicator (caused by loadFirstPageIntent)
// 2. show the items with the first page (caused by loadFirstPageIntent)
// 3. show loading next page indicator
// 4. show next page content (plus original first page content)
//
List<FeedItem> expectedDataAfterNextPage = Arrays.asList(new SectionHeader("category1"), mockProductsFirstPage.get(0), mockProductsFirstPage.get(1), mockProductsFirstPage.get(2), new AdditionalItemsLoadable(2, "category1", false, null), new SectionHeader("category2"), mockProductsNextPage.get(0), mockProductsNextPage.get(1), mockProductsNextPage.get(2), new AdditionalItemsLoadable(1, "category2", false, null));
HomeViewState nextPageLoading = new HomeViewState.Builder().data(expectedDataAfterFristPage).nextPageLoading(true).build();
HomeViewState nextPage = new HomeViewState.Builder().data(expectedDataAfterNextPage).build();
// Check if as expected
robot.assertViewStateRendered(loadingFirstPage, firstPage, nextPageLoading, nextPage);
//
// fire pull to refresh intent
//
// Error: no connection to server
mockWebServer.shutdown();
robot.firePullToRefreshIntent();
//
// we expect that 6 view.render() events happened with the following HomeViewState:
// 1. show loading indicator (caused by loadFirstPageIntent)
// 2. show the items with the first page (caused by loadFirstPageIntent)
// 3. show loading next page indicator
// 4. show next page content (plus original first page content)
// 5. show loading - pull to refresh indicator
// 6. show error loading pull to refresh (plus original first page + next page content)
//
HomeViewState pullToRefreshLoading = new HomeViewState.Builder().data(expectedDataAfterNextPage).pullToRefreshLoading(true).build();
HomeViewState pullToRefreshError = new HomeViewState.Builder().data(expectedDataAfterNextPage).pullToRefreshError(new ConnectException()).build();
robot.assertViewStateRendered(loadingFirstPage, firstPage, nextPageLoading, nextPage, pullToRefreshLoading, pullToRefreshError);
}
use of okhttp3.Connection in project Fast-Android-Networking by amitshekhariitbhu.
the class HttpLoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
if (hasRequestBody) {
// them to be included (when available) so there values are known.
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
logger.log("");
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
} else {
logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
}
}
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
logger.log("<-- HTTP FAILED: " + e);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (!isPlaintext(buffer)) {
logger.log("");
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
use of okhttp3.Connection in project okhttp by square.
the class ResponseCacheTest method assertCached.
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
int expectedResponseCode = responseCode;
server = new MockWebServer();
MockResponse mockResponse = new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(responseCode).setBody("ABCDE").addHeader("WWW-Authenticate: challenge");
if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) {
// We forbid bodies for 204 and 205.
mockResponse.setBody("");
}
server.enqueue(mockResponse);
if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
// 408's are a bit of an outlier because we may repeat the request if we encounter this
// response code. In this scenario, there are 2 responses: the initial 408 and then the 200
// because of the retry. We just want to ensure the initial 408 isn't cached.
expectedResponseCode = 200;
server.enqueue(new MockResponse().setHeader("Cache-Control", "no-store").setBody("FGHIJ"));
}
server.start();
URL url = server.url("/").url();
HttpURLConnection connection = openConnection(url);
assertEquals(expectedResponseCode, connection.getResponseCode());
// Exhaust the content stream.
readAscii(connection);
CacheResponse cached = cache.get(url.toURI(), "GET", null);
if (shouldPut) {
assertNotNull(Integer.toString(responseCode), cached);
} else {
assertNull(Integer.toString(responseCode), cached);
}
// tearDown() isn't sufficient; this test starts multiple servers
server.shutdown();
}
use of okhttp3.Connection in project okhttp by square.
the class ResponseCacheTest method redirectToCachedResult.
@Test
public void redirectToCachedResult() throws Exception {
server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").setBody("ABC"));
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: /foo"));
server.enqueue(new MockResponse().setBody("DEF"));
assertEquals("ABC", readAscii(openConnection(server.url("/foo").url())));
RecordedRequest request1 = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request1.getRequestLine());
assertEquals(0, request1.getSequenceNumber());
assertEquals("ABC", readAscii(openConnection(server.url("/bar").url())));
RecordedRequest request2 = server.takeRequest();
assertEquals("GET /bar HTTP/1.1", request2.getRequestLine());
assertEquals(1, request2.getSequenceNumber());
// an unrelated request should reuse the pooled connection
assertEquals("DEF", readAscii(openConnection(server.url("/baz").url())));
RecordedRequest request3 = server.takeRequest();
assertEquals("GET /baz HTTP/1.1", request3.getRequestLine());
assertEquals(2, request3.getSequenceNumber());
}
Aggregations