List of usage examples for com.squareup.okhttp Callback Callback
Callback
From source file:com.teddoll.movies.reciever.MovieSync.java
License:Apache License
public static void getReviews(final OkHttpClient client, Movie movie, final OnGetReviewsListener listener) { if (listener == null) throw new IllegalArgumentException("OnGetReviewsListener cannot be null"); Request request = new Request.Builder().url(String.format(Locale.US, REVIEW_URL, movie.id)) .addHeader("Accept", "application/json").build(); client.newCall(request).enqueue(new Callback() { @Override/*from w w w .j a v a 2s . c o m*/ public void onFailure(Request request, IOException e) { listener.onReviews(new ArrayList<Review>(0)); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { try { JSONObject json = new JSONObject(response.body().string()); JSONArray array = json.optJSONArray("results"); Gson gson = new Gson(); Type type = new TypeToken<List<Review>>() { }.getType(); List<Review> reviews = gson.fromJson(array.toString(), type); listener.onReviews(reviews); } catch (JSONException e) { listener.onReviews(new ArrayList<Review>(0)); } } else { listener.onReviews(new ArrayList<Review>(0)); } } }); }
From source file:com.weather.hackathon.model.LayersFetcher.java
License:Open Source License
/** * Requests a new set of available tiles in the background. A successful load will notify the * {@link LayersResultListener} if one has been {@link #setLayersResultListener(LayersResultListener) set}. * * <p/> Only successful fetches are reported. Errors are logged and ignored. Listener's callback * {@link LayersResultListener#onLayersReceived(Collection) method} will be called on the same thread that * created this instance.//from w ww . ja v a2 s. co m * * <p/> The layers fetched will contain the {@link Layer#getTimestamp() timestamp} of the newest tiles for * that layer. */ public void fetchAsync() { Request request = new Request.Builder().url("http://hackathon.weather.com/Maps/jsonserieslist.do").build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(TAG, "Unable to retrieve list of layers", e); } @Override public void onResponse(Response response) throws IOException { try { if (response.isSuccessful()) { final String json = response.body().string(); final Collection<Layer> layers = Layers.parseJson(json); handler.post(new Runnable() { @Override public void run() { if (layersResultListener != null) { layersResultListener.onLayersReceived(layers); } } }); } else { Log.e(TAG, "Error request list of layers. statusCode=" + response.code()); } } catch (JsonSyntaxException e) { Log.e(TAG, "Unable to parse list of layers", e); } } }); }
From source file:com.yingke.shengtai.adapter.ChatAllHistoryAdapter.java
License:Open Source License
public void postRequest(final TextView text, final String userName, final Map<String, String> map) { FormEncodingBuilder builder = new FormEncodingBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue()); }// ww w . j a v a2s . c om RequestBody formBody = builder.build(); Request request = new Request.Builder().url(IApi.URL_IMID_NAME).header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json").addHeader("Content-Type", "application/json;charset=utf-8") .addHeader("Content-Length", "length").post(formBody).build(); RequestManager.getOkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String json = response.body().string(); ImidToNickNameData data = JosnUtil.gson.fromJson(json, new TypeToken<ImidToNickNameData>() { }.getType()); if (data != null && TextUtils.equals("1", "1")) { try { User user = new User(); user.setNick(data.getDetaillist().get(0).getDisplayname()); user.setUsername(data.getDetaillist().get(0).getImid()); user.setSex(data.getDetaillist().get(0).getSex()); userDao.saveContactsss(user); UIHandler.sendEmptyMessage(0); } catch (Exception e) { } } } } }); }
From source file:com.yingke.shengtai.adapter.ChatSaleAdapter.java
License:Open Source License
public void postRequest(final TextView text, final String userName, final Map<String, String> map) { FormEncodingBuilder builder = new FormEncodingBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue()); }/*from w w w . j a v a 2 s .c o m*/ RequestBody formBody = builder.build(); Request request = new Request.Builder().url(IApi.URL_IMID_NAME).header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json").addHeader("Content-Type", "application/json;charset=utf-8") .addHeader("Content-Length", "length").post(formBody).build(); RequestManager.getOkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String json = response.body().string(); ImidToNickNameData data = JosnUtil.gson.fromJson(json, new TypeToken<ImidToNickNameData>() { }.getType()); if (data != null && TextUtils.equals("1", data.getResult() + "")) { try { User user = new User(); user.setNick(data.getDetaillist().get(0).getDisplayname()); user.setUsername(data.getDetaillist().get(0).getImid()); user.setSex(data.getDetaillist().get(0).getSex()); userDao.saveContactsss(user); UIHandler.sendEmptyMessage(0); } catch (Exception e) { } } } } }); }
From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java
License:Open Source License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "bi.id: " + beaconInstance.id + ", bi.googleType: " + beaconInstance.googleType); View rootView = inflater.inflate(R.layout.fragment_manage_beacon, container, false); advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type); advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id); status = (TextView) rootView.findViewById(R.id.status); placeId = (TextView) rootView.findViewById(R.id.placeId); placeId.setOnClickListener(new View.OnClickListener() { @Override//from ww w .j a v a2 s.c o m public void onClick(View v) { editLatLngAction(); } }); latLng = (TextView) rootView.findViewById(R.id.latLng); latLng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); mapView = (ImageView) rootView.findViewById(R.id.mapView); mapView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); expectedStability = (TextView) rootView.findViewById(R.id.expectedStability); expectedStability.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability"); final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.stability_enums, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner spinner = new Spinner(getActivity()); spinner.setAdapter(adapter); // Set the position of the spinner to the current value. if (beaconInstance.expectedStability != null && !beaconInstance.expectedStability.equals(BeaconInstance.STABILITY_UNSPECIFIED)) { for (int i = 0; i < spinner.getCount(); i++) { if (beaconInstance.expectedStability.equals(spinner.getItemAtPosition(i))) { spinner.setSelection(i); } } } builder.setView(spinner); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beaconInstance.expectedStability = (String) spinner.getSelectedItem(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); description = (TextView) rootView.findViewById(R.id.description); description.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description"); final EditText editText = new EditText(getActivity()); editText.setText(description.getText()); builder.setView(editText); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beaconInstance.description = editText.getText().toString(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); actionButton = (Button) rootView.findViewById(R.id.actionButton); decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton); decommissionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon") .setMessage("Are you sure you want to decommission this beacon? This operation is " + "irreversible and the beacon cannot be registered again") .setPositiveButton("Decommission", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Callback decommissionCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { beaconInstance.status = BeaconInstance.STATUS_DECOMMISSIONED; updateBeacon(); } else { String body = response.body().string(); logErrorAndToast("Unsuccessful decommissionBeacon request: " + body); } } }; client.decommissionBeacon(decommissionCallback, beaconInstance.getBeaconName()); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }); attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider); attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel); attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout); // Fetch the namespace for the developer console project ID. We redraw the UI once that // request completes. // TODO: cache this. Callback listNamespacesCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); JSONArray namespaces = json.getJSONArray("namespaces"); // At present there can be only one namespace. String tmp = namespaces.getJSONObject(0).getString("namespaceName"); if (tmp.startsWith("namespaces/")) { namespace = tmp.substring("namespaces/".length()); } else { namespace = tmp; } redraw(); } catch (JSONException e) { Log.e(TAG, "JSONException", e); } } else { logErrorAndToast("Unsuccessful listNamespaces request: " + body); } } }; client.listNamespaces(listNamespacesCallback); return rootView; }
From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java
License:Open Source License
private void updateBeacon() { // If the beacon hasn't been registered or was decommissioned, redraw the view and let the // commit happen in the parent action. if (beaconInstance.status.equals(BeaconInstance.UNREGISTERED) || beaconInstance.status.equals(BeaconInstance.STATUS_DECOMMISSIONED)) { redraw();//from w w w .ja v a2 s. c o m return; } Callback updateBeaconCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { beaconInstance = new BeaconInstance(new JSONObject(body), beaconInstance); } catch (JSONException e) { logErrorAndToast("Failed JSON creation from response: " + body, e); return; } redraw(); } else { logErrorAndToast("Unsuccessful updateBeacon request: " + body); } } }; JSONObject json; try { json = beaconInstance.toJson(); } catch (JSONException e) { logErrorAndToast("JSONException in creating update request", e); return; } client.updateBeacon(updateBeaconCallback, beaconInstance.getBeaconName(), json); }
From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java
License:Open Source License
private View.OnClickListener createActionButtonOnClickListener(final String status) { if (status == null) { return null; }/*from w w w . ja va2 s . com*/ if (!status.equals(BeaconInstance.STATUS_ACTIVE) && !status.equals(BeaconInstance.STATUS_INACTIVE) && !status.equals(BeaconInstance.UNREGISTERED)) { return null; } return new View.OnClickListener() { @Override public void onClick(View v) { actionButton.setEnabled(false); Callback onClickCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(final Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); if (json.length() > 0) { // Activate, deactivate and decommission return empty responses. Register returns // a beacon object. beaconInstance = new BeaconInstance(json, beaconInstance); } updateBeacon(); } catch (JSONException e) { logErrorAndToast("Failed JSON creation from response: " + body, e); } } else { logErrorAndToast("Unsuccessful request: " + body); } actionButton.setEnabled(true); } }; switch (status) { case BeaconInstance.STATUS_ACTIVE: client.activateBeacon(onClickCallback, beaconInstance.getBeaconName()); break; case BeaconInstance.STATUS_INACTIVE: client.deactivateBeacon(onClickCallback, beaconInstance.getBeaconName()); break; case BeaconInstance.UNREGISTERED: try { JSONObject activeBeacon = beaconInstance.toJson().put("status", BeaconInstance.STATUS_ACTIVE); client.registerBeacon(onClickCallback, activeBeacon); } catch (JSONException e) { toast("JSONException: " + e); Log.e(TAG, "Failed to convert beaconInstance to JSON", e); return; } break; } } }; }
From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java
License:Open Source License
private View.OnClickListener makeInsertAttachmentOnClickListener(final Button insertButton, final TextView namespaceTextView, final EditText typeEditText, final EditText dataEditText) { return new View.OnClickListener() { @Override//from w w w.ja v a 2 s . c om public void onClick(View v) { final String namespace = namespaceTextView.getText().toString(); if (namespace.length() == 0) { toast("namespace cannot be empty"); return; } String type = typeEditText.getText().toString(); if (type.length() == 0) { toast("type cannot be empty"); return; } final String data = dataEditText.getText().toString(); if (data.length() == 0) { toast("data cannot be empty"); return; } Utils.setEnabledViews(false, insertButton); JSONObject body = buildCreateAttachmentJsonBody(namespace, type, data); Callback createAttachmentCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); Utils.setEnabledViews(false, insertButton); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); attachmentsTable.addView(makeAttachmentRow(json), 2); namespaceTextView.setText(namespace); typeEditText.setText(""); typeEditText.requestFocus(); dataEditText.setText(""); insertButton.setEnabled(true); } catch (JSONException e) { logErrorAndToast("JSONException in building attachment data", e); } } else { logErrorAndToast("Unsuccessful createAttachment request: " + body); } Utils.setEnabledViews(true, insertButton); } }; client.createAttachment(createAttachmentCallback, beaconInstance.getBeaconName(), body); } }; }
From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java
License:Open Source License
private void listAttachments() { Callback listAttachmentsCallback = new Callback() { @Override/*from w ww .j a v a 2 s.c o m*/ public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); attachmentsTable.removeAllViews(); attachmentsTable.addView(makeAttachmentTableHeader()); attachmentsTable.addView(makeAttachmentInsertRow()); if (json.length() == 0) { // No attachment data return; } JSONArray attachments = json.getJSONArray("attachments"); for (int i = 0; i < attachments.length(); i++) { JSONObject attachment = attachments.getJSONObject(i); attachmentsTable.addView(makeAttachmentRow(attachment)); } } catch (JSONException e) { Log.e(TAG, "JSONException in fetching attachments", e); } } else { logErrorAndToast("Unsuccessful listAttachments request: " + body); } } }; client.listAttachments(listAttachmentsCallback, beaconInstance.getBeaconName()); }
From source file:es.upv.grycap.coreutils.fiber.test.HighlyConcurrencyTest.java
License:Apache License
private void runTest(final Http2Client client) throws Exception { // prepare the test final Waiter waiter = new Waiter(); for (int i = 0; i < 100; i++) { final int id = i; client.asyncGet(/*from w w w .j a va 2 s. com*/ new StringBuilder(MOCK_SERVER_BASE_URL).append("/test/concurrent/").append(i).toString(), of("application/json"), true, new Callback() { @Override public void onResponse(final Response response) throws IOException { waiter.assertTrue(response.isSuccessful()); final String payload = response.body().source().readUtf8(); waiter.assertThat(payload, allOf(notNullValue(), equalTo(new StringBuilder("Response-to-").append(id).toString()))); waiter.resume(); } @Override public void onFailure(final Request request, final IOException throwable) { waiter.fail(throwable); } }); } waiter.await(30l, TimeUnit.SECONDS, 100); }