use of com.tonyodev.fetch2.Request in project cw-omnibus by commonsguy.
the class LoadThread method run.
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(SO_URL).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Reader in = response.body().charStream();
BufferedReader reader = new BufferedReader(in);
SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class);
reader.close();
EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
} else {
Log.e(getClass().getSimpleName(), response.toString());
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
}
use of com.tonyodev.fetch2.Request in project cw-omnibus by commonsguy.
the class Downloader method onHandleIntent.
@Override
public void onHandleIntent(Intent i) {
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
try {
String filename = i.getData().getLastPathSegment();
NotificationCompat.Builder builder = buildForeground(filename);
final Notification notif = builder.build();
startForeground(FOREGROUND_ID, notif);
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
root.mkdirs();
File output = new File(root, filename);
if (output.exists()) {
output.delete();
}
final ProgressResponseBody.Listener progressListener = new ProgressResponseBody.Listener() {
long lastUpdateTime = 0L;
@Override
public void onProgressChange(long bytesRead, long contentLength, boolean done) {
long now = SystemClock.uptimeMillis();
if (now - lastUpdateTime > 1000) {
notif.contentView.setProgressBar(android.R.id.progress, (int) contentLength, (int) bytesRead, false);
mgr.notify(FOREGROUND_ID, notif);
lastUpdateTime = now;
}
}
};
Interceptor nightTrain = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response original = chain.proceed(chain.request());
Response.Builder b = original.newBuilder().body(new ProgressResponseBody(original.body(), progressListener));
return (b.build());
}
};
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(nightTrain).build();
Request request = new Request.Builder().url(i.getData().toString()).build();
Response response = client.newCall(request).execute();
String contentType = response.header("Content-type");
BufferedSink sink = Okio.buffer(Okio.sink(new File(output.getPath())));
sink.writeAll(response.body().source());
sink.close();
stopForeground(true);
raiseNotification(contentType, output, null);
} catch (IOException e2) {
stopForeground(true);
raiseNotification(null, null, e2);
}
}
use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.
the class AuthenticationTests method canCRUDWebAppWithAuthentication.
@Test
@Ignore("Need facebook developer account")
public void canCRUDWebAppWithAuthentication() throws Exception {
// Create with new app service plan
WebApp webApp1 = appServiceManager.webApps().define(WEBAPP_NAME_1).withRegion(Region.US_WEST).withNewResourceGroup(RG_NAME_1).withNewWindowsPlan(PricingTier.BASIC_B1).defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK).withFacebook("appId", "appSecret").attach().create();
Assert.assertNotNull(webApp1);
Assert.assertEquals(Region.US_WEST, webApp1.region());
AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId());
Assert.assertNotNull(plan1);
Assert.assertEquals(Region.US_WEST, plan1.region());
Assert.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier());
Request request = new Request.Builder().url("http://" + webApp1.defaultHostName()).get().build();
String response = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build().newCall(request).execute().body().string();
Assert.assertTrue(response.contains("do not have permission"));
// Update
webApp1.update().updateAuthentication().withAnonymousAuthentication().parent().apply();
request = new Request.Builder().url("http://" + webApp1.defaultHostName()).get().build();
response = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build().newCall(request).execute().body().string();
Assert.assertFalse(response.contains("do not have permission"));
}
use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.
the class KeyVaultCredentials method applyCredentialsFilter.
@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url();
Map<String, String> challengeMap = cache.getCachedChallenge(url);
if (challengeMap != null) {
// Get the bearer token
String credential = getAuthenticationCredentials(challengeMap);
Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
return chain.proceed(newRequest);
} else {
// response
return chain.proceed(chain.request());
}
}
});
// Caches the challenge for failed request and re-send the request with
// access token.
clientBuilder.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// if challenge is not cached then extract and cache it
String authenticateHeader = response.header(WWW_AUTHENTICATE);
Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
// Cache the challenge
cache.addCachedChallenge(response.request().url(), challengeMap);
// Get the bearer token from the callback by providing the
// challenges
String credential = getAuthenticationCredentials(challengeMap);
if (credential == null) {
return null;
}
// be cached anywhere in our code.
return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
}
});
}
use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.
the class MockIntegrationTestBase method recordRequestAndResponse.
private Response recordRequestAndResponse(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
NetworkCallRecord networkCallRecord = new NetworkCallRecord();
networkCallRecord.Headers = new HashMap<>();
try {
if (request.header("Content-Type") != null) {
networkCallRecord.Headers.put("Content-Type", request.header("Content-Type"));
}
if (request.header("x-ms-version") != null) {
networkCallRecord.Headers.put("x-ms-version", request.header("x-ms-version"));
}
if (request.header("User-Agent") != null) {
networkCallRecord.Headers.put("User-Agent", request.header("User-Agent"));
}
networkCallRecord.Method = request.method();
networkCallRecord.Uri = applyRegex(request.url().toString().replaceAll("\\?$", ""));
} catch (Exception e) {
}
Response response = chain.proceed(chain.request());
networkCallRecord.Response = new HashMap<>();
try {
networkCallRecord.Response.put("StatusCode", Integer.toString(response.code()));
extractResponseData(networkCallRecord.Response, response);
// remove pre-added header if this is a waiting or redirection
if (networkCallRecord.Response.get("Body").contains("<Status>InProgress</Status>") || Integer.parseInt(networkCallRecord.Response.get("StatusCode")) == HttpStatus.SC_TEMPORARY_REDIRECT) {
} else {
synchronized (testRecord.networkCallRecords) {
testRecord.networkCallRecords.add(networkCallRecord);
}
}
} catch (Exception e) {
}
return response;
}
Aggregations