List of usage examples for com.squareup.okhttp Callback Callback
Callback
From source file:newer.project.superwechat.activity.LoginActivity.java
License:Open Source License
/** ??? */ private void loginSuccess() { try {// w w w . jav a2 s. c o m // ** ?logout??? // ** manually load all local groups and EMGroupManager.getInstance().loadAllGroups(); EMChatManager.getInstance().loadAllConversations(); //? final OkHttpUtils2<Message> utils = new OkHttpUtils2<Message>(); utils.url(SuperWeChatApplication.SERVER_ROOT).addParam(I.KEY_REQUEST, I.REQUEST_DOWNLOAD_AVATAR) .addParam(I.AVATAR_TYPE, currentUsername).doInBackground(new Callback() { @Override public void onFailure(Request request, IOException e) { Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { String path = I.AVATAR_TYPE_USER_PATH + I.BACKSLASH + currentUsername + I.AVATAR_SUFFIX_JPG; File file = OnSetAvatarListener.getAvatarFile(LoginActivity.this, path); utils.downloadFile(response, file, false); } }).execute(null); // ?? runOnUiThread(new Runnable() { @Override public void run() { new DownloadContactListTask(LoginActivity.this, currentUsername).execute(); new DownloadAllGroupTask(LoginActivity.this, currentUsername).execute(); new DownloadPublicGroupTask(LoginActivity.this, currentUsername, I.PAGE_ID_DEFAULT, I.PAGE_SIZE_DEFAULT).execute(); } }); initializeContacts(); } catch (Exception e) { e.printStackTrace(); // ????? runOnUiThread(new Runnable() { public void run() { pd.dismiss(); DemoHXSDKHelper.getInstance().logout(true, null); Toast.makeText(getApplicationContext(), R.string.login_failure_failed, Toast.LENGTH_SHORT) .show(); } }); return; } // ?nickname ios?nick boolean updatenick = EMChatManager.getInstance() .updateCurrentUserNick(SuperWeChatApplication.currentUserNick.trim()); if (!updatenick) { Log.e("LoginActivity", "update current user nick fail"); } if (!LoginActivity.this.isFinishing() && pd.isShowing()) { pd.dismiss(); } // ? Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); }
From source file:org.chromium.cronet_sample_apk.CronetSampleActivity.java
License:Open Source License
private void makeRequest(Request request) { final Request mRequest = request; if (OkHttpSynchronousFlag) { new Thread(new Runnable() { public void run() { try { Response response = mOKHttpClient.newCall(mRequest).execute(); final String receivedData = response.body().string(); final String url = mRequest.urlString(); final String text = "Completed " + url + " (" + response.code() + ")"; CronetSampleActivity.this.runOnUiThread(new Runnable() { public void run() { mOkhttpResultText.setText(text); mOkhttpReceiveDataText.setText(receivedData); }/*from w ww . j a v a 2 s. c om*/ }); if (!OKHttpFinishFlag) { OKHttpFinishFlag = true; Log.d(TAG, "set okhttp finish flag to true"); } } catch (IOException e) { final String url = mRequest.urlString(); final String text = "Failed " + url + " (" + e.getMessage() + ")"; CronetSampleActivity.this.runOnUiThread(new Runnable() { public void run() { mOkhttpResultText.setText(text); } }); if (!OKHttpFinishFlag) { OKHttpFinishFlag = true; Log.d(TAG, "set okhttp finish flag to true"); } } } }).start(); } else { mOKHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { final String url = mUrl; final String text = "Failed " + url + " (" + e.getMessage() + ")"; CronetSampleActivity.this.runOnUiThread(new Runnable() { public void run() { mOkhttpResultText.setText(text); } }); if (!OKHttpFinishFlag) { OKHttpFinishFlag = true; Log.d(TAG, "set okhttp finish flag to true"); } } @Override public void onResponse(Response response) throws IOException { final String receivedData = response.body().string(); Log.d(TAG, receivedData); final String url = mUrl; final String text = "Completed " + url + " (" + response.code() + ")"; CronetSampleActivity.this.runOnUiThread(new Runnable() { public void run() { mOkhttpResultText.setText(text); mOkhttpReceiveDataText.setText(receivedData); } }); if (!OKHttpFinishFlag) { OKHttpFinishFlag = true; Log.d(TAG, "set okhttp finish flag to true"); } } }); } }
From source file:org.floens.chan.core.manager.ReplyManager.java
License:Open Source License
public void postPass(String token, String pin, final PassListener passListener) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); formBuilder.add("act", "do_login"); formBuilder.add("id", token); formBuilder.add("pin", pin); Request.Builder request = new Request.Builder().url(ChanUrls.getPassUrl()).post(formBuilder.build()); makeOkHttpCall(request, new Callback() { @Override/* w w w . ja v a 2s.c o m*/ public void onFailure(Request request, IOException e) { final PassResponse res = new PassResponse(); res.isError = true; res.message = context.getString(R.string.pass_error); runUI(new Runnable() { public void run() { passListener.onResponse(res); } }); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { onFailure(response.request(), null); return; } String responseString = response.body().string(); response.body().close(); final PassResponse res = new PassResponse(); if (responseString.contains("Your device is now authorized")) { List<String> cookies = response.headers("Set-Cookie"); String passId = null; for (String cookie : cookies) { try { List<HttpCookie> parsedList = HttpCookie.parse(cookie); for (HttpCookie parsed : parsedList) { if (parsed.getName().equals("pass_id") && !parsed.getValue().equals("0")) { passId = parsed.getValue(); } } } catch (IllegalArgumentException ignored) { } } if (passId != null) { res.passId = passId; res.message = "Success! Your device is now authorized."; } else { res.isError = true; res.message = "Could not get pass id"; } } else { res.isError = true; if (responseString.contains("Your Token must be exactly 10 characters")) { res.message = "Incorrect token"; } else if (responseString.contains("You have left one or more fields blank")) { res.message = "You have left one or more fields blank"; } else if (responseString.contains("Incorrect Token or PIN")) { res.message = "Incorrect Token or PIN"; } else { res.unknownError = true; } } runUI(new Runnable() { public void run() { passListener.onResponse(res); } }); } }); }
From source file:org.floens.chan.core.manager.ReplyManager.java
License:Open Source License
public void postDelete(final SavedReply reply, boolean onlyImageDelete, final DeleteListener listener) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); formBuilder.add(Integer.toString(reply.no), "delete"); if (onlyImageDelete) { formBuilder.add("onlyimgdel", "on"); }//from w ww . java 2 s . com formBuilder.add("mode", "usrdel"); formBuilder.add("pwd", reply.password); Request.Builder request = new Request.Builder().url(ChanUrls.getDeleteUrl(reply.board)) .post(formBuilder.build()); makeOkHttpCall(request, new Callback() { @Override public void onFailure(Request request, IOException e) { final DeleteResponse res = new DeleteResponse(); res.isNetworkError = true; runUI(new Runnable() { @Override public void run() { listener.onResponse(res); } }); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { onFailure(response.request(), null); return; } String responseString = response.body().string(); response.body().close(); final DeleteResponse res = new DeleteResponse(); res.responseData = responseString; if (responseString.contains("You must wait longer before deleting this post")) { res.isUserError = true; res.isTooSoonError = true; } else if (responseString.contains("Password incorrect")) { res.isUserError = true; res.isInvalidPassword = true; } else if (responseString.contains("You cannot delete a post this old")) { res.isUserError = true; res.isTooOldError = true; } else if (responseString.contains("Updating index")) { res.isSuccessful = true; } runUI(new Runnable() { @Override public void run() { listener.onResponse(res); } }); } }); }
From source file:org.floens.chan.core.manager.ReplyManager.java
License:Open Source License
private void postReplyInternal(final Reply reply, final ReplyListener replyListener, String captchaHash) { reply.password = Long.toHexString(random.nextLong()); MultipartBuilder formBuilder = new MultipartBuilder(); formBuilder.type(MultipartBuilder.FORM); formBuilder.addFormDataPart("mode", "regist"); formBuilder.addFormDataPart("pwd", reply.password); if (reply.resto >= 0) { formBuilder.addFormDataPart("resto", String.valueOf(reply.resto)); }// w ww . j av a 2s. co m formBuilder.addFormDataPart("name", reply.name); formBuilder.addFormDataPart("email", reply.email); if (!TextUtils.isEmpty(reply.subject)) { formBuilder.addFormDataPart("sub", reply.subject); } formBuilder.addFormDataPart("com", reply.comment); if (captchaHash != null) { formBuilder.addFormDataPart("g-recaptcha-response", captchaHash); } if (reply.file != null) { formBuilder.addFormDataPart("upfile", reply.fileName, RequestBody.create(MediaType.parse("application/octet-stream"), reply.file)); } if (reply.spoilerImage) { formBuilder.addFormDataPart("spoiler", "on"); } Request.Builder request = new Request.Builder().url(ChanUrls.getReplyUrl(reply.board)) .post(formBuilder.build()); if (reply.usePass) { request.addHeader("Cookie", "pass_id=" + reply.passId); } makeOkHttpCall(request, new Callback() { @Override public void onFailure(Request request, IOException e) { final ReplyResponse res = new ReplyResponse(); res.isNetworkError = true; runUI(new Runnable() { public void run() { replyListener.onResponse(res); } }); } @Override public void onResponse(Response response) throws IOException { final ReplyResponse res = new ReplyResponse(); if (response.isSuccessful()) { onReplyPosted(response.body().string(), reply, res); response.body().close(); } else { res.isNetworkError = true; } runUI(new Runnable() { public void run() { replyListener.onResponse(res); } }); } }); }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(MetricDataPayloadBuilder payloadBuilder, long waitMillis) { String jsonPayload = "?"; try {/*from www . j av a 2 s.c o m*/ // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // get the payload in JSON format jsonPayload = payloadBuilder.toPayload().toString(); // build the REST URL... StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()); url.append("metrics/data"); // now send the REST request Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), tenantIdHeader, jsonPayload); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreMetricData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // HTTP status of 200 means success; anything else is an error if (response.code() != 200) { IOException e = new IOException("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); log.errorFailedToStoreMetricData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } else { // looks like everything stored successfully diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints()); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } catch (Throwable t) { log.errorFailedToStoreMetricData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(AvailDataPayloadBuilder payloadBuilder, long waitMillis) { String jsonPayload = "?"; try {/*from w ww . j a v a2s. c o m*/ // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // get the payload in JSON format jsonPayload = payloadBuilder.toPayload().toString(); // build the REST URL... StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()); url.append("availability/data"); // now send the REST request Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), tenantIdHeader, jsonPayload); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreAvailData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // HTTP status of 200 means success; anything else is an error if (response.code() != 200) { IOException e = new IOException("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); log.errorFailedToStoreAvailData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } else { // looks like everything stored successfully diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints()); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } catch (Throwable t) { log.errorFailedToStoreAvailData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(MetricTagPayloadBuilder payloadBuilder, long waitMillis) { Map<String, String> jsonPayloads = null; try {/*from w ww. j a va 2 s . co m*/ // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // get the payload(s) jsonPayloads = payloadBuilder.toPayload(); // build the REST URL... String url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()).toString(); // The way the metrics REST API works is you can only add tags for one metric at a time // so loop through each metric ID and send one REST request for each one. for (Map.Entry<String, String> jsonPayload : jsonPayloads.entrySet()) { String relativePath = jsonPayload.getKey(); // this identifies the metric (e.g. "gauges/<id>") String tagsJson = jsonPayload.getValue(); String currentUrl = url + relativePath + "/tags"; // now send the REST request Request request = this.httpClientBuilder.buildJsonPutRequest(currentUrl, tenantIdHeader, tagsJson); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreMetricTags(e, tagsJson); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // HTTP status of 200 means success; anything else is an error if (response.code() != 200) { IOException e = new IOException("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); log.errorFailedToStoreMetricTags(e, tagsJson); diagnostics.getStorageErrorRate().mark(1); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } } catch (Throwable t) { log.errorFailedToStoreMetricTags(t, (jsonPayloads == null) ? "?" : jsonPayloads.toString()); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java
License:Apache License
@Override public void run() { Request request = null;// www . j a va2 s. c om try { String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier(); request = new Request.Builder().url(uri).addHeader("Accept", JSON_MEDIA_TYPE.toString()).get().build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { if (e instanceof ConnectException) { LOG.warn("Reading job failed: target " + baseuri + " seems down"); } else { LOG.warn("Reading job failed: " + e); } } @Override public void onResponse(Response response) throws IOException { if (response.code() == 204) { return; // No content, nothing to do } String content = response.body().string(); OpsRequest map = Util.fromJson(content, OpsRequest.class); String action = map.getAction(); String operationId = map.getId(); String tenantId = map.getTenantId(); // "[Local~/deployment=hawkular-avail-creator.war]" String resId = map.getResourceId(); resId = resId.substring(resId.indexOf("~/") + 2); if (resId.endsWith("]")) { resId = resId.substring(0, resId.length() - 1); } Address address = Address.parse(resId); LOG.debug("Executing " + address + "/:" + action); ModelNode mrequest = JBossASClient.createRequest(action, address); try { ModelNode result = asClient.execute(mrequest); OpsResult outcome = toOutcome(result); LOG.debug("Outcome " + outcome); submitResult(operationId, tenantId, outcome); } catch (Exception e) { throw new IOException(e); } } }); } catch (Throwable t) { LOG.warn("Error: " + t.getMessage()); } }
From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java
License:Apache License
private void submitResult(String operationId, String tenantId, OpsResult result) throws Exception { Request request;//from ww w . j av a 2 s .c om String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier() + "/" + operationId; String json = Util.toJson(result); RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json); request = new Request.Builder().url(uri).post(body).addHeader("Hawkular-Tenant", tenantId).build(); // Asynchronous POST httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { LOG.warn("Sending of response failed: " + e); } @Override public void onResponse(Response response) throws IOException { if (response.code() != 200) { LOG.warn("Send failed : " + response.message()); } } }); }