Example usage for com.squareup.okhttp Response isSuccessful

List of usage examples for com.squareup.okhttp Response isSuccessful

Introduction

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

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

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;
    }/*from  w  ww.j  ava  2  s  .  co  m*/
    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//from  w  w w.  jav  a2s  . c o  m
        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 ava2  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//  w  w w .  j a va  2  s  . com
        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
 *///  w w w. ja  v 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 2  s . co 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) {
                        // 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

@Override
public synchronized List<Object> exploreFolder(@NonNull CFolder folder, int offset)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from  ww  w. jav  a2s.c  o  m

    List<Object> list = new ArrayList<>();
    String folderId = folder.getId();
    Uri uri = Uri.parse(API_BASE_URL);
    String url = uri.buildUpon().appendEncodedPath("folders/" + folderId + "/items")
            .appendQueryParameter("limit", "500").appendQueryParameter("offset", String.valueOf(offset)).build()
            .toString();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            int total = jsonObject.getInt("total_count");
            // return null if no item found
            if (total == 0)
                return null;

            JSONArray entries = jsonObject.getJSONArray("entries");
            list.addAll(createFilteredItemsList(entries, folder));
            // suspect search result over 500 items
            if (total > 500 && total - list.size() > 0) {
                list.addAll(exploreFolder(folder, 500));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

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

License:Apache License

@Override
public synchronized CFolder getFolderInfo(@NonNull String folderId) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }// w  w w.  j av a 2s  .  c  o  m

    if (TextUtils.isEmpty(folderId))
        return null;

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folderId)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // new file created
            JSONObject jsonObject = new JSONObject(response.body().string());
            return buildFolder(jsonObject);
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

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

License:Apache License

@Override
public synchronized CFolder createFolder(@NonNull String name, @Nullable CFolder parent)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from   w  ww.ja v a 2s  .  co m
    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
        params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId()));
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).post(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful() && response.code() == 201) {
            // new folder created
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

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

License:Apache License

@Override
public synchronized CFolder renameFolder(@NonNull CFolder folder, String name) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*from   ww  w  . ja  v  a 2 s  .  c o m*/

    // exit if root or same name
    if (folder.isRoot() || folder.getName().equals(name))
        return folder;

    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folder.getId())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).put(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // return folder object
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}