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.google.sample.beaconservice.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 (beacon.status.equals(Beacon.UNREGISTERED) || beacon.status.equals(Beacon.STATUS_DECOMMISSIONED)) {
        redraw();// www  .j a v  a 2  s  .c om
        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 {
                    beacon = new Beacon(new JSONObject(body));
                } catch (JSONException e) {
                    logErrorAndToast("Failed JSON creation from response: " + body, e);
                    return;
                }
                redraw();
            } else {
                logErrorAndToast("Unsuccessful updateBeacon request: " + body);
            }
        }
    };

    JSONObject json;
    try {
        json = beacon.toJson();
    } catch (JSONException e) {
        logErrorAndToast("JSONException in creating update request", e);
        return;
    }

    client.updateBeacon(updateBeaconCallback, beacon.getBeaconName(), json);
}

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

License:Open Source License

private View.OnClickListener createActionButtonOnClickListener(final String status) {
    if (status == null) {
        return null;
    }/*  w  ww  . j  av  a 2 s . com*/
    if (!status.equals(Beacon.STATUS_ACTIVE) && !status.equals(Beacon.STATUS_INACTIVE)
            && !status.equals(Beacon.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.
                                beacon = new Beacon(json);
                            }
                            updateBeacon();
                        } catch (JSONException e) {
                            logErrorAndToast("Failed JSON creation from response: " + body, e);
                        }
                    } else {
                        logErrorAndToast("Unsuccessful request: " + body);
                    }
                    actionButton.setEnabled(true);
                }
            };
            switch (status) {
            case Beacon.STATUS_ACTIVE:
                client.activateBeacon(onClickCallback, beacon.getBeaconName());
                break;
            case Beacon.STATUS_INACTIVE:
                client.deactivateBeacon(onClickCallback, beacon.getBeaconName());
                break;
            case Beacon.UNREGISTERED:
                try {
                    JSONObject activeBeacon = beacon.toJson().put("status", Beacon.STATUS_ACTIVE);
                    client.registerBeacon(onClickCallback, activeBeacon);
                } catch (JSONException e) {
                    toast("JSONException: " + e);
                    Log.e(TAG, "Failed to convert beacon to JSON", e);
                    return;
                }
                break;
            }
        }
    };
}

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

License:Open Source License

private Button createAttachmentDeleteButton(final int viewId, final String attachmentName) {
    final Button button = new Button(getActivity());
    button.setLayoutParams(BUTTON_COL_LAYOUT);
    button.setText("-");
    button.setOnClickListener(new View.OnClickListener() {
        @Override/*  w  ww . ja  v a 2s  .  c om*/
        public void onClick(View v) {
            Utils.setEnabledViews(false, button);
            Callback deleteAttachmentCallback = 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()) {
                        attachmentsTable.removeView(attachmentsTable.findViewById(viewId));
                    } else {
                        String body = response.body().string();
                        logErrorAndToast("Unsuccessful deleteAttachment request: " + body);
                    }
                }
            };
            client.deleteAttachment(deleteAttachmentCallback, attachmentName);
        }
    });
    return button;
}

From source file:com.google.sample.beaconservice.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 www . j a va  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;
            }
            final 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, beacon.getBeaconName(), body);
        }
    };
}

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

License:Open Source License

private void listAttachments() {
    Callback listAttachmentsCallback = new Callback() {
        @Override/*from  w w w.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, beacon.getBeaconName());
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Ensure that the access token is still valid
 * Access token can be expired or revoked by user
 * Try to refresh the access token if it is expired
 *///from   www  . j  av  a 2 s .c o  m
private void validateAccessToken() {
    Request request = getUserInfoRequest(mAccessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            if (mPrepareListener != null)
                mPrepareListener.onPrepareFail(e);
            Log.e(TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() && response.code() == 200) {
                if (mPrepareListener != null)
                    mPrepareListener.onPrepareSuccessful();
            } else {
                switch (response.code()) {
                case 401:
                    // unauthorized
                    refreshAccessToken();
                    break;
                default:
                    break;
                }
                Log.e(TAG, response.code() + ": " + response.body().string());
            }
        }
    });
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Try to get a fresh access token using the refresh token
 *//*from   ww w.  j av  a 2s  .  c om*/
private void refreshAccessToken() {
    final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
    if (!TextUtils.isEmpty(refreshToken)) {
        Request request = new Request.Builder().url(TOKEN_URL).post(getRefreshTokenBody(refreshToken)).build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());

                resetAccount();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    // convert string into json
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Map<String, String> tokenInfo = extractAccessToken(jsonObject);
                        mCloudProvider.updateAccount(mAccount, tokenInfo);
                        mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
                        // validate again
                        validateAccessToken();
                    } catch (JSONException e) {
                        // no remedy
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                    }
                } else {
                    Log.e(TAG, response.code() + ": " + response.body().string());
                    resetAccount();
                }
            }
        });
    } else {
        resetAccount();
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Remove the staled account and add a new one
 *//* w w w  .j ava  2 s .c o m*/
private void resetAccount() {
    logout(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

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

        }
    });
    // use Authenticator to update account
    mCloudProvider.removeAccount(mAccount);
    mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
}

From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java

License:Apache License

/**
 * Ensure that the access token is still valid
 * Access token can be expired or revoked by user
 * Try to refresh the access token if it is expired
 *//*w  w  w.j av  a2s .  c o  m*/
private void validateAccessToken() {
    Request request = getEndPointRequest(mAccessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            if (mPrepareListener != null)
                mPrepareListener.onPrepareFail(e);
            Log.e(TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() && response.code() == 200) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    mContentUrl = jsonObject.getString("contentUrl");
                    mMetadataUrl = jsonObject.getString("metadataUrl");

                    if (mPrepareListener != null)
                        mPrepareListener.onPrepareSuccessful();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                    if (mPrepareListener != null)
                        mPrepareListener.onPrepareFail(e);
                }
            } else {
                switch (response.code()) {
                case 401:
                    // unauthorized
                    refreshAccessToken();
                    break;
                default:
                    break;
                }
                Log.e(TAG, response.code() + ": " + response.body().string());
            }
        }
    });
}

From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java

License:Apache License

/**
 * Try to get a fresh access token using the refresh token
 *///from   w  ww  .jav  a  2 s .c o m
private void refreshAccessToken() {
    final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
    if (!TextUtils.isEmpty(refreshToken)) {
        Request request = new Request.Builder().url(TOKEN_URL).post(getRefreshTokenBody(refreshToken)).build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());

                resetAccount();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    // convert string into json
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Map<String, String> tokenInfo = extractAccessToken(jsonObject);
                        mCloudProvider.updateAccount(mAccount, tokenInfo);
                        mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
                        // validate again
                        validateAccessToken();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                    }
                } else {
                    Log.e(TAG, response.code() + ": " + response.body().string());
                    resetAccount();
                }

            }
        });
    } else {
        resetAccount();
    }
}