Example usage for com.squareup.okhttp Callback Callback

List of usage examples for com.squareup.okhttp Callback Callback

Introduction

In this page you can find the example usage for com.squareup.okhttp Callback Callback.

Prototype

Callback

Source Link

Usage

From source file:com.facebook.react.devsupport.DevServerHelper.java

License:Open Source License

public void launchChromeDevtools() {
    Request request = new Request.Builder().url(createLaunchChromeDevtoolsCommandUrl()).build();
    mClient.newCall(request).enqueue(new Callback() {
        @Override//from www  .j a  v a 2 s.  com
        public void onFailure(Request request, IOException e) {
            // ignore HTTP call response, this is just to open a debugger page and there is no reason
            // to report failures from here
        }

        @Override
        public void onResponse(Response response) throws IOException {
            // ignore HTTP call response - see above
        }
    });
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

public void send(final Request request, final RequestListener listener) {
    c.newCall(buildReq(request)).enqueue(new Callback() {
        @Override/*from w w  w.ja v  a2  s.c  o  m*/
        public void onFailure(com.squareup.okhttp.Request r, IOException e) {
            try {
                listener.onFailure(request, e);
            } catch (Throwable t) {
                LOG.warn("Error invoking listener", t);
            }
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response r) throws IOException {
            try {
                if (r != null) {
                    listener.onResponse(new Response(r));
                } else {
                    listener.onFailure(request,
                            new IOException("response is null, review internal okhttp framework."));
                }
            } catch (Throwable t) {
                LOG.warn("Error invoking listener", t);
            } finally {
                IOUtils.closeQuietly(r.body());
            }
        }
    });
}

From source file:com.fysl.app.main.LoginActivity.java

License:Open Source License

private void loginInserver(String tel, String password) {

    final ProgressDialog progressDialog = new ProgressDialog(this);

    progressDialog.setMessage("...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();//from  ww w . j a  v  a2 s . com

    // ???

    RequestBody formBody = new FormEncodingBuilder()

            .add("tel", tel).add("password", MD5Util.getMD5String(password)).build();

    Request request = new Request.Builder().url(Constant.URL_LOGIN).post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "?...", Toast.LENGTH_SHORT)
                            .show();
                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    progressDialog.dismiss();

                }

            });
            // System.out.println("response--->" + arg0.body().string());

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();

                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    final JSONObject userJson = json.getJSONObject("user");
                    DemoApplication.getInstance().savaUserInfo(userJson);
                    // ?
                    // SDK?

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                            // TODO Auto-generated method stub
                            loginHuanxin(userJson);
                        }

                    });
                }

            }
        }

    });

}

From source file:com.fysl.app.main.LoginActivity.java

License:Open Source License

private void getFriendsInfoInServer(String allFriends) {

    final ProgressDialog progressDialog = new ProgressDialog(this);

    progressDialog.setMessage("?...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();//from  w ww  .jav a 2  s. c o  m

    // ???

    RequestBody formBody = new FormEncodingBuilder()

            .add("allFriends", allFriends).build();

    Request request = new Request.Builder().url(Constant.URL_GET_FRIENDS).post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "?...", Toast.LENGTH_SHORT)
                            .show();
                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    progressDialog.dismiss();

                }

            });
            // System.out.println("response--->" + arg0.body().string());

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();

                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    final JSONArray friends = json.getJSONArray("friends");
                    Map<String, EaseUser> usermap = new HashMap<String, EaseUser>();
                    for (int i = 0; i < friends.size(); i++) {
                        JSONObject friend = friends.getJSONObject(i);
                        EaseUser user = JSON2User.getUser(friend);
                        usermap.put(user.getUsername(), user);

                    }

                    DemoHelper.getInstance().getContactList().putAll(usermap);
                    UserDao dao = new UserDao(LoginActivity.this);
                    dao.saveContactList(new ArrayList(usermap.values()));

                    // // ?
                    // // SDK?
                    //
                    // runOnUiThread(new Runnable() {
                    //
                    // @Override
                    // public void run() {
                    // // TODO Auto-generated method stub
                    // loginHuanxin(friends);
                    // }
                    //
                    // });
                }

            }
        }

    });

}

From source file:com.fysl.app.ui.AddContactActivity.java

License:Open Source License

private void searchUserInServer(String value) {

    final ProgressDialog pd = new ProgressDialog(AddContactActivity.this);
    pd.setCanceledOnTouchOutside(false);
    pd.setMessage("?...");
    pd.show();//  w w  w. j a v a  2  s .  com

    RequestBody formBody = new FormEncodingBuilder().add("uid", value)

            .build();

    // Constant.KEY_TEL
    Request request = new Request.Builder().url(Constant.URL_SEARCH_USER).post(formBody)

            .build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    pd.dismiss();
                    Toast.makeText(AddContactActivity.this, "??", Toast.LENGTH_SHORT).show();

                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();
                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            pd.dismiss();

                        }

                    });

                    JSONObject userInfo = json.getJSONObject("user");

                    startActivity(new Intent(AddContactActivity.this, UserDetailActivity.class)
                            .putExtra("userInfo", userInfo.toJSONString()));

                } else {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT)
                                    .show();
                        }

                    });

                }

            } else {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pd.dismiss();
                    }

                });
                throw new IOException("Unexpected code " + arg0);
            }

        }

    });

}

From source file:com.github.mmatczuk.ablb.benchmark.OkHttpAsync.java

License:Apache License

@Override
public void prepare(final Benchmark benchmark) {
    concurrencyLevel = benchmark.concurrencyLevel;
    targetBacklog = benchmark.targetBacklog;

    client = new OkHttpClient();
    client.setDispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel,
            benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())));

    callback = new Callback() {
        @Override/* ww w  .j  a v  a2s . c  o  m*/
        public void onFailure(Request request, IOException e) {
            System.out.println("Failed: " + e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            ResponseBody body = response.body();
            long total = readAllAndClose(body.byteStream());
            long finish = System.nanoTime();
            if (VERBOSE) {
                long start = (Long) response.request().tag();
                System.out.printf("Transferred % 8d bytes in %4d ms%n", total,
                        TimeUnit.NANOSECONDS.toMillis(finish - start));
            }
            requestsInFlight.decrementAndGet();
        }
    };
}

From source file:com.github.pockethub.android.ui.comment.RawCommentFragment.java

License:Apache License

@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
        showProgressIndeterminate(R.string.loading);
        ImageBinPoster.post(getActivity(), data.getData(), new Callback() {
            @Override/*www.ja va 2  s . c om*/
            public void onFailure(Request request, IOException e) {
                dismissProgress();
                showImageError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                dismissProgress();
                if (response.isSuccessful()) {
                    insertImage(ImageBinPoster.getUrl(response.body().string()));
                } else {
                    showImageError();
                }
            }
        });
    }
}

From source file:com.github.pockethub.android.ui.issue.EditIssueActivity.java

License:Apache License

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
        progressDialog = new MaterialDialog.Builder(this).content(R.string.loading).progress(true, 0).build();
        progressDialog.show();//from w w w  .j a v a2  s. c  om
        ImageBinPoster.post(this, data.getData(), new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                progressDialog.dismiss();
                showImageError();
            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                progressDialog.dismiss();
                if (response.isSuccessful()) {
                    insertImage(ImageBinPoster.getUrl(response.body().string()));
                } else {
                    showImageError();
                }
            }
        });
    }
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

License:Open Source License

private void insertIntoListAndFetchStatus(final Beacon beacon) {
    arrayAdapter.add(beacon);/*from   w w w.j  a v  a  2s.  c  o  m*/
    arrayAdapter.sort(RSSI_COMPARATOR);
    Callback getBeaconCallback = new Callback() {
        @Override
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            Log.e(TAG, String.format("Failed request: %s, IOException %s", request, e));
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            Beacon fetchedBeacon;
            switch (response.code()) {
            case 200:
                try {
                    String body = response.body().string();
                    Log.d(Constants.TEST_TAG, body);
                    fetchedBeacon = new Beacon(new JSONObject(body));
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                    return;
                }
                break;
            case 403:
                fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.NOT_AUTHORIZED, beacon.rssi);
                break;
            case 404:
                fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.UNREGISTERED, beacon.rssi);
                break;
            default:
                Log.e(TAG, "Unhandled beacon service response: " + response);
                return;
            }
            int pos = arrayAdapter.getPosition(beacon);
            arrayList.set(pos, fetchedBeacon);
            updateArrayAdapter();
        }
    };
    client.getBeacon(getBeaconCallback, beacon.getBeaconName());
    Log.d(Constants.TEST_TAG, "Beacon Name: " + beacon.getBeaconName());
}

From source file:com.google.sample.beaconservice.ManageBeaconFragment.java

License:Open Source License

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    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/*w w w  .j  a va  2  s  . c  om*/
        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 (beacon.expectedStability != null
                    && !beacon.expectedStability.equals(Beacon.STABILITY_UNSPECIFIED)) {
                for (int i = 0; i < spinner.getCount(); i++) {
                    if (beacon.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) {
                    beacon.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) {
                    beacon.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()) {
                                        beacon.status = Beacon.STATUS_DECOMMISSIONED;
                                        updateBeacon();
                                    } else {
                                        String body = response.body().string();
                                        logErrorAndToast("Unsuccessful decommissionBeacon request: " + body);
                                    }
                                }
                            };
                            client.decommissionBeacon(decommissionCallback, beacon.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;
                    }
                    Log.d(Constants.TEST_TAG, "Namespace " + namespace);
                    redraw();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                }
            } else {
                logErrorAndToast("Unsuccessful listNamespaces request: " + body);
            }
        }
    };
    client.listNamespaces(listNamespacesCallback);
    return rootView;
}