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:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

License:Open Source License

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*from   w  w w . j  a  va 2s  .  c o m*/
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);

            final HttpUrl.Builder url = HttpUrl.parse(Constants.BITEASY_API_URL).newBuilder();
            url.addPathSegment("outputs");
            url.addQueryParameter("per_page", "MAX");
            url.addQueryParameter("operator", "AND");
            url.addQueryParameter("spent_state", "UNSPENT");
            for (final Address address : addresses)
                url.addQueryParameter("address[]", address.toBase58());

            log.debug("trying to request wallet balance from {}", url.build());

            final Request.Builder request = new Request.Builder();
            request.url(url.build());
            request.cacheControl(new CacheControl.Builder().noCache().build());
            request.header("Accept-Charset", "utf-8");
            if (userAgent != null)
                request.header("User-Agent", userAgent);

            final Call call = Constants.HTTP_CLIENT.newCall(request.build());
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    final JSONObject json = new JSONObject(content);

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IOException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = Sha256Hash.wrap(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = Constants.HEX
                                .decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);

                        if (tx.getOutputs().size() > uxtoIndex) {
                            // Work around not being able to replace outputs on transactions
                            final List<TransactionOutput> outputs = new ArrayList<TransactionOutput>(
                                    tx.getOutputs());
                            final TransactionOutput dummy = outputs.set(uxtoIndex, output);
                            checkState(dummy.getValue().equals(Coin.NEGATIVE_SATOSHI),
                                    "Index %s must be dummy output", uxtoIndex);
                            // Remove and re-add all outputs
                            tx.clearOutputs();
                            for (final TransactionOutput o : outputs)
                                tx.addOutput(o);
                        } else {
                            // Fill with dummies as needed
                            while (tx.getOutputs().size() < uxtoIndex)
                                tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                        Coin.NEGATIVE_SATOSHI, new byte[] {}));

                            // Add the real output
                            tx.addOutput(output);
                        }
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final int responseCode = response.code();
                    final String responseMessage = response.message();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);
                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}

From source file:de.schildbach.wallet.util.HttpGetThread.java

License:Open Source License

@Override
public void run() {
    log.debug("querying \"{}\"...", url);

    final Request.Builder request = new Request.Builder();
    request.url(url);/*from  ww w .  j a v a2s .  c  o m*/
    request.header("Accept-Charset", "utf-8");
    if (userAgent != null)
        request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final long serverTime = response.headers().getDate("Date").getTime();
            final BufferedReader reader = new BufferedReader(response.body().charStream());
            final String line = reader.readLine().trim();
            reader.close();

            handleLine(line, serverTime);
        }
    } catch (final Exception x) {
        handleException(x);
    }
}

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  w w w  . java 2 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();// w w  w  .ja  v a  2s.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.  jav  a 2s.c om*/
    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// w w w  .  j ava2s  .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/* 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, beaconInstance.getBeaconName());
}

From source file:edu.umich.flowfence.smartthings.SmartThingsService.java

License:Apache License

private void pullDevices(final String deviceTypeStr) {
    new Thread() {
        public void run() {

            String eURL = endpointsURL + "?access_token=" + OAuthToken;
            Request getEndpoints = new Request.Builder().url(eURL).build();

            try {
                Response resp = httpClient.newCall(getEndpoints).execute();

                if (resp.isSuccessful()) {
                    String jsonStr = resp.body().string();
                    JSONArray jobj = new JSONArray(jsonStr);

                    installationURL = jobj.getJSONObject(0).getString("url");
                    fullBaseURL = baseURL + installationURL;

                    Log.i(TAG, fullBaseURL);
                }//www.j  av  a  2 s  .  com

                //now get all devices
                String getSwitchesURL = fullBaseURL + "/" + deviceTypeStr + "?access_token=" + OAuthToken;
                Log.i(TAG, "making request: " + getSwitchesURL);
                Request getSwitches = new Request.Builder().url(getSwitchesURL).build();
                Response switchesResp = httpClient.newCall(getSwitches).execute();

                if (switchesResp.isSuccessful()) {
                    String jsonResp = switchesResp.body().string();
                    JSONObject switchObj = new JSONObject(jsonResp);

                    int dType = -1;
                    if (deviceTypeStr.equals(DEVICE_TYPE_URI_SWITCH))
                        dType = SmartDevice.TYPE_SWITCH;
                    else if (deviceTypeStr.equals(DEVICE_TYPE_URI_LOCKS))
                        dType = SmartDevice.TYPE_LOCK;

                    Iterator<String> iter = switchObj.keys();
                    while (iter.hasNext()) {
                        String switchName = iter.next();
                        String switchId = switchObj.getString(switchName);
                        SmartDevice aSwitch = new SmartDevice(switchName, switchId, dType);
                        devices.add(aSwitch);
                    }
                }

            } catch (IOException ioe) {
                Log.e(TAG, "error: " + ioe);
            } catch (JSONException jsone) {
                Log.e(TAG, "error: " + jsone);
            }
        }
    }.start();
}

From source file:edu.umich.oasis.study.smartdevresponderexemplar.SmartThingsService.java

License:Apache License

private void pullDevices() {
    new Thread() {
        public void run() {

            String eURL = endpointsURL + "?access_token=" + OAuthToken;
            Request getEndpoints = new Request.Builder().url(eURL).build();

            try {
                Response resp = httpClient.newCall(getEndpoints).execute();

                if (resp.isSuccessful()) {
                    String jsonStr = resp.body().string();
                    JSONArray jobj = new JSONArray(jsonStr);

                    installationURL = jobj.getJSONObject(0).getString("url");
                    fullBaseURL = baseURL + installationURL;

                    Log.i(TAG, fullBaseURL);
                }/*from   w w w  .j  a  va2  s.c o  m*/

                //now get all devices
                String getSwitchesURL = fullBaseURL + "/switches?access_token=" + OAuthToken;
                Log.i(TAG, "making request: " + getSwitchesURL);
                Request getSwitches = new Request.Builder().url(getSwitchesURL).build();
                Response switchesResp = httpClient.newCall(getSwitches).execute();

                if (switchesResp.isSuccessful()) {
                    String jsonResp = switchesResp.body().string();
                    JSONObject switchObj = new JSONObject(jsonResp);

                    Iterator<String> iter = switchObj.keys();
                    while (iter.hasNext()) {
                        String switchName = iter.next();
                        String switchId = switchObj.getString(switchName);
                        SmartSwitch aSwitch = new SmartSwitch(switchName, switchId);
                        switches.add(aSwitch);
                    }
                }

            } catch (IOException ioe) {
                Log.e(TAG, "error: " + ioe);
            } catch (JSONException jsone) {
                Log.e(TAG, "error: " + jsone);
            }
        }
    }.start();
}

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(//  w ww  .  j a  v  a  2 s. c  o  m
                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);
}