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.SecUpwN.AIMSICD.AIMSICD.java

void selectDrawerItem(int position) {
    NavDrawerItem selectedItem = mNavConf.getNavItems().get(position);
    String title = selectedItem.getLabel();

    switch (selectedItem.getId()) {
    case DrawerMenu.ID.MAIN.PHONE_SIM_DETAILS:
        openFragment(deviceFragment);/*from  w w  w .  j a v  a  2s . c  o  m*/
        title = getString(R.string.app_name_short);
        break;
    case DrawerMenu.ID.MAIN.CURRENT_TREAT_LEVEL:
        openFragment(cellInfoFragment);
        title = getString(R.string.app_name_short);
        break;
    case DrawerMenu.ID.MAIN.AT_COMMAND_INTERFACE:
        openFragment(atCommandFragment);
        title = getString(R.string.app_name_short);
        break;
    case DrawerMenu.ID.MAIN.DB_VIEWER:
        openFragment(dbViewerFragment);
        title = getString(R.string.app_name_short);
        break;
    case DrawerMenu.ID.APPLICATION.UPLOAD_LOCAL_BTS_DATA:
        // Request uploading here?
        new RequestTask(this, com.SecUpwN.AIMSICD.utils.RequestTask.DBE_UPLOAD_REQUEST).execute("");
        // no string needed for csv based upload
        break;
    case DrawerMenu.ID.MAIN.ANTENNA_MAP_VIEW:
        openFragment(mapFragment);
        title = getString(R.string.app_name_short);
        break;
    case DrawerMenu.ID.SETTINGS.BACKUP_DB:
        new RequestTask(this, RequestTask.BACKUP_DATABASE).execute();
        break;
    }

    if (selectedItem.getId() == DrawerMenu.ID.SETTINGS.RESTORE_DB) {
        if (CellTracker.LAST_DB_BACKUP_VERSION < AIMSICDDbAdapter.DATABASE_VERSION) {
            Helpers.msgLong(this, getString(R.string.unable_to_restore_backup_from_previous_database_version));
        } else {
            new RequestTask(this, RequestTask.RESTORE_DATABASE).execute();
        }
    } else if (selectedItem.getId() == DrawerMenu.ID.SETTINGS.RESET_DB) {
        // WARNING! This deletes the entire database, thus any subsequent DB access will FC app.
        //          Therefore we need to either restart app or run AIMSICDDbAdapter, to rebuild DB.
        //          See: https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/581 and Helpers.java
        Helpers.askAndDeleteDb(this);

    } else if (selectedItem.getId() == DrawerMenu.ID.APPLICATION.DOWNLOAD_LOCAL_BTS_DATA) {
        downloadBtsDataIfApiKeyAvailable();
    } else if (selectedItem.getId() == DrawerMenu.ID.MAIN.ALL_CURRENT_CELL_DETAILS) {
        if (CellTracker.OCID_API_KEY != null && !CellTracker.OCID_API_KEY.equals("NA")) {

            //TODO: Use Retrofit for that
            StringBuilder sb = new StringBuilder();
            sb.append("http://www.opencellid.org/cell/get?key=").append(CellTracker.OCID_API_KEY);

            if (mAimsicdService.getCell().getMCC() != Integer.MAX_VALUE) {
                sb.append("&mcc=").append(mAimsicdService.getCell().getMCC());
            }

            if (mAimsicdService.getCell().getMNC() != Integer.MAX_VALUE) {
                sb.append("&mnc=").append(mAimsicdService.getCell().getMNC());
            }

            if (mAimsicdService.getCell().getLAC() != Integer.MAX_VALUE) {
                sb.append("&lac=").append(mAimsicdService.getCell().getLAC());
            }

            if (mAimsicdService.getCell().getCID() != Integer.MAX_VALUE) {
                sb.append("&cellid=").append(mAimsicdService.getCell().getCID());
            }

            sb.append("&format=xml");

            Request request = new Request.Builder().url(sb.toString()).get().build();

            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        List<Cell> cellList = new StackOverflowXmlParser().parse(response.body().byteStream());
                        AIMSICD.this.processFinish(cellList);
                    } catch (XmlPullParserException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            Helpers.sendMsg(this, getString(R.string.no_opencellid_key_detected));
        }
    } else if (selectedItem.getId() == DrawerMenu.ID.APPLICATION.QUIT) {
        try {
            if (mAimsicdService.isSmsTracking()) {
                mAimsicdService.stopSmsTracking();
            }
        } catch (Exception ee) {
            log.warn("Exception in smstracking module: " + ee.getMessage());
        }

        if (mAimsicdService != null) {
            mAimsicdService.onDestroy();
        }
        //Close database on Exit
        log.info("Closing db from DrawerMenu.ID.APPLICATION.QUIT");
        new AIMSICDDbAdapter(getApplicationContext()).close();
        finish();
    }

    mDrawerList.setItemChecked(position, true);

    if (selectedItem.updateActionBarTitle()) {
        setTitle(title);
    }

    if (this.mDrawerLayout.isDrawerOpen(this.mDrawerList)) {
        mDrawerLayout.closeDrawer(mDrawerList);
    }
}

From source file:com.secupwn.aimsicd.ui.fragments.DeviceFragment.java

@NonNull
private Callback getOpenCellIdResponseCallback() {
    return new Callback() {
        @Override/*  w  ww. ja  v a2 s .  c om*/
        public void onFailure(Request request, IOException e) {
            Handler refresh = new Handler(Looper.getMainLooper());
            refresh.post(new Runnable() {
                public void run() {
                    refreshFailed();
                }
            });
        }

        @Override
        public void onResponse(final Response response) throws IOException {
            Handler refresh = new Handler(Looper.getMainLooper());
            refresh.post(new Runnable() {
                public void run() {
                    Cell cell = responseToCell(response);
                    processFinish(cell);
                }
            });
        }
    };
}

From source file:com.sonaive.v2ex.sync.api.UserIdentityApi.java

License:Open Source License

public void verifyUserIdentity(final String accountName,
        final WeakReference<LoginHelper.Callbacks> callbacksRef) {

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(mUrl + "?username=" + accountName).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        @Override/*from   w  w  w  .  j  av a2  s.c  o  m*/
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", "IOException");
            if (callbacksRef != null) {
                callbacksRef.get().onIdentityCheckedFailed(result);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            JsonObject result = new JsonObject();
            if (response.code() == 200) {
                String responseBody = response.body().string();
                try {
                    JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
                    String status = jsonObject.get("status").getAsString();
                    if (status != null && status.equals("found")) {
                        result.addProperty("result", "ok");
                        LOGD(TAG, "userInfo: " + responseBody);
                        AccountUtils.setActiveAccount(mContext, accountName);
                        V2exDataHandler dataHandler = new V2exDataHandler(mContext);

                        Bundle data = new Bundle();
                        data.putString(Api.ARG_RESULT, responseBody);
                        data.putString(V2exDataHandler.ARG_DATA_KEY, V2exDataHandler.DATA_KEY_MEMBERS);
                        dataHandler.applyData(new Bundle[] { data });

                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedSuccess(result);
                        }
                    } else if (status != null && status.equals("notfound")) {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_user_not_found));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    } else {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_unknown_error));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    }
                } catch (JsonSyntaxException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "JsonSyntaxException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                } catch (UnsupportedOperationException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "UnsupportedOperationException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (callbacksRef != null) {
                    callbacksRef.get().onIdentityCheckedFailed(result);
                }
            }
            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** Get once code for sign in */
private void getOnceCodeAndSignin() {
    Request request = new Request.Builder().url(Api.API_URLS.get(Api.API_SIGNIN)).build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override// w w w.j a  v a 2  s .  c  om
        public void onFailure(Request request, IOException e) {
            final JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            Activity activity = getActivity("getOnceCodeAndSignin()");
            if (activity == null) {
                return;
            }
            if (e != null) {
                result.addProperty("err_msg", activity.getString(R.string.err_io_exception));
            } else {
                result.addProperty("err_msg", activity.getString(R.string.err_get_once_failed));
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            final JsonObject result = new JsonObject();

            Pattern pattern = Pattern.compile("<input type=\"hidden\" value=\"([0-9]+)\" name=\"once\" />");
            final Matcher matcher = pattern.matcher(response.body().string());
            Activity activity = getActivity("getOnceCodeAndSignin()");
            if (activity == null) {
                return;
            }
            if (matcher.find()) {
                String code = matcher.group(1);
                signIn(code);
            } else {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", activity.getString(R.string.err_get_once_failed));
            }
        }
    });
}

From source file:com.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** Get signed in account info(node collections, account name), need cookie */
private void getUserInfo() {
    Request request = new Request.Builder().url(Api.API_URLS.get(Api.API_MY_NODES)).build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override//from w ww  .j  a v a2  s.  co  m
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", mAppContext.getString(R.string.err_get_node_collections_failed));
            if (mCallbacksRef != null) {
                mCallbacksRef.get().onNodeCollectionFetchedFailed(result);
            }
        }

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

            JsonObject result = new JsonObject();

            if (response.code() == 200) {
                Pattern userPattern = Pattern.compile("<a href=\"/member/([^\"]+)\" class=\"top\">");
                Matcher userMatcher = userPattern.matcher(response.body().string());
                if (userMatcher.find()) {

                    String accountName = userMatcher.group(1);
                    Pattern collectionPattern = Pattern.compile("</a>&nbsp; <a href=\"/go/([^\"]+)\">");
                    Matcher collectionMatcher = collectionPattern.matcher(response.body().string());
                    List<String> collections = new ArrayList<>();
                    if (collectionMatcher.find()) {
                        collections.add(collectionMatcher.group(1));
                        while (collectionMatcher.find()) {
                            collections.add(collectionMatcher.group(1));
                        }
                    }
                    // TODO add the user node collections into database
                    LOGD(TAG, "Get user: " + accountName + " node collections: " + collections.toString());
                    result.addProperty("result", "ok");
                    if (mCallbacksRef != null) {
                        mCallbacksRef.get().onNodeCollectionFetchedSuccess(result);
                    }
                } else {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", mAppContext.getString(R.string.err_get_my_nodes_failed));
                    if (mCallbacksRef != null) {
                        mCallbacksRef.get().onNodeCollectionFetchedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (mCallbacksRef != null) {
                    mCallbacksRef.get().onIdentityCheckedFailed(result);
                }

            } else {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", mAppContext.getString(R.string.err_unknown_error));
                if (mCallbacksRef != null) {
                    mCallbacksRef.get().onIdentityCheckedFailed(result);
                }
            }

            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.survivingwithandroid.ubiapp.UbidotsClient.java

License:Apache License

public void handleUbidots(String varId, String apiKey, final UbiListener listener) {

    final List<Value> results = new ArrayList<>();

    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().addHeader("X-Auth-Token", apiKey)
            .url("http://things.ubidots.com/api/v1.6/variables/" + varId + "/values").build();

    client.newCall(req).enqueue(new Callback() {
        @Override/*from   w  ww  .  ja  v  a2  s  .c om*/
        public void onFailure(Request request, IOException e) {
            Log.d("Chart", "Network error");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            Log.d("Chart", body);

            try {
                JSONObject jObj = new JSONObject(body);
                JSONArray jRes = jObj.getJSONArray("results");
                for (int i = 0; i < jRes.length(); i++) {
                    JSONObject obj = jRes.getJSONObject(i);
                    Value val = new Value();
                    val.timestamp = obj.getLong("timestamp");
                    val.value = (float) obj.getDouble("value");
                    results.add(val);
                }

                listener.onDataReady(results);

            } catch (JSONException jse) {
                jse.printStackTrace();
            }

        }
    });

}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    progressDialog = ProgressDialog.show(this, "Getting results", "Processing image", true);
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Image captured and saved to fileUri specified in the Intent

            try {
                postImage(new Callback() {
                    @Override// w ww .java2s.c  o  m
                    public void onFailure(Request request, IOException ioe) {
                        // Something went wrong
                        Log.e("Network error", "Error making image post request");
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String responseStr = response.body().string();
                            // Do what you want to do with the response.
                            Log.d("response", "responseSTR: " + responseStr);
                            System.out.println(responseStr);
                            try {
                                JSONObject myObject = new JSONObject(responseStr);
                                final String token = myObject.getString("token");

                                checkForKeywords(token);
                            } catch (JSONException je) {
                                Log.e("Post response not JSON", je.getMessage());
                            }
                        } else {
                            // Request not successful
                            System.out.println("Request not successful");
                            System.out.println(response.code());
                            System.out.println(response.message());
                            System.out.println(response.body().string());
                            progressDialog.dismiss();
                        }
                    }
                });
            } catch (Throwable e) {
                Log.e("Image call error", e.getMessage());
                progressDialog.dismiss();
            }
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            progressDialog.dismiss();
        } else {
            // Image capture failed, advise user
            progressDialog.dismiss();
        }
    }
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

private void checkForKeywords(final String token) {
    this.runOnUiThread(new Runnable() {
        public void run() {
            progressDialog.setMessage("Identifying image");

            final Handler h = new Handler();
            final int delay = 3000; // milliseconds

            h.postDelayed(new Runnable() {
                public void run() {
                    //do something
                    try {
                        getKeywords(token, new Callback() {
                            @Override
                            public void onFailure(Request request, IOException ioe) {
                                // Something went wrong
                                Log.e("Network error", "Error making token request");
                                progressDialog.dismiss();
                            }/*  ww w  .ja  v  a2s .co  m*/

                            @Override
                            public void onResponse(Response response) throws IOException {
                                if (response.isSuccessful()) {
                                    String responseStr = response.body().string();
                                    // Do what you want to do with the response.
                                    System.out.println(responseStr);
                                    try {
                                        JSONObject myObject = new JSONObject(responseStr);
                                        String status = myObject.getString("status");
                                        if (status.equals("completed")) {
                                            keywords = myObject.getString("name");
                                            gotKeywords = true;
                                        }
                                    } catch (JSONException je) {
                                        Log.e("Get response not JSON", je.getMessage());
                                        progressDialog.dismiss();
                                    }
                                } else {
                                    // Request not successful
                                    System.out.println("Request not successful");
                                    System.out.println(response.code());
                                    System.out.println(response.message());
                                    System.out.println(response.body().string());
                                    progressDialog.dismiss();
                                }
                            }
                        });
                    } catch (Throwable e) {
                        Log.e("Token call error", e.getMessage());
                        progressDialog.dismiss();
                    }

                    if (!gotKeywords) {
                        h.postDelayed(this, delay);
                    } else {
                        System.out.println(keywords);

                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }

                        Intent intent = new Intent(context, MainViewPagerActivity.class);
                        intent.putExtra("keywords", keywords);
                        intent.putExtra("barcode", "null");
                        startActivity(intent);
                    }
                }
            }, delay);
        }
    });
}

From source file:com.teddoll.movies.reciever.MovieSync.java

License:Apache License

public static synchronized void SyncData(final OkHttpClient client, final MovieProvider movieCache,
        final OnFetchCompleteListener listener) {
    if (inProcess)
        return;/*from   w w w  . j a  va 2s  . com*/
    inProcess = true;

    Request popRequest = new Request.Builder().url(POP_URL).addHeader("Accept", "application/json").build();
    Request rateRequest = new Request.Builder().url(RATE_URL).addHeader("Accept", "application/json").build();
    Request genresRequest = new Request.Builder().url(GENRE_URL).addHeader("Accept", "application/json")
            .build();
    requestCount = 3;
    pop = null;
    rate = null;
    genres = null;
    client.newCall(popRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    pop = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            onComplete(movieCache, listener);
        }
    });

    client.newCall(rateRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    rate = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            onComplete(movieCache, listener);
        }
    });
    client.newCall(genresRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("genres");
                    genres = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            onComplete(movieCache, listener);
        }
    });

}

From source file:com.teddoll.movies.reciever.MovieSync.java

License:Apache License

public static void getVideos(final OkHttpClient client, Movie movie, final OnGetVideosListener listener) {
    if (listener == null)
        throw new IllegalArgumentException("OnGetVideosListener cannot be null");
    Request request = new Request.Builder().url(String.format(Locale.US, VIDEO_URL, movie.id))
            .addHeader("Accept", "application/json").build();

    client.newCall(request).enqueue(new Callback() {
        @Override/*from w  ww. ja va 2  s .  c  o  m*/
        public void onFailure(Request request, IOException e) {
            listener.onVideos(new ArrayList<Video>(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<Video>>() {
                    }.getType();
                    List<Video> vids = gson.fromJson(array.toString(), type);
                    listener.onVideos(vids);
                } catch (JSONException e) {
                    listener.onVideos(new ArrayList<Video>(0));
                }
            } else {
                listener.onVideos(new ArrayList<Video>(0));
            }

        }
    });
}