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:it.analysis.ReportDumpTest.java

License:Open Source License

private void verifyUrl(String url) throws IOException {
    HttpUrl httpUrl = HttpUrl.parse(url);
    Request request = new Request.Builder().url(httpUrl).get().build();
    Response response = new OkHttpClient().newCall(request).execute();
    assertThat(response.isSuccessful()).as(httpUrl.toString()).isTrue();
    assertThat(response.body().string()).as(httpUrl.toString()).isNotEmpty();
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type//w w w.  j a va2s .co m
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            if (response.body() != null) {
                try {
                    response.body().close();
                } catch (IOException e) {
                    throw new ApiException(response.message(), e, response.code(),
                            response.headers().toMultimap());
                }
            }
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

License:Apache License

private void getPostAll() {

    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";

    Request request = new Request.Builder().url(firstUrl).build();

    int count = 0;

    try {/*ww  w .  j a  va  2s  .c o  m*/

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful()) {
            mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                    .setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException();
        } else {

            //Take the response and parse the JSON
            JSONObject JObject = new JSONObject(response.body().string());
            JSONArray posts = JObject.optJSONArray("posts");

            //Store the data into the two objects, meta gets the next page later on.
            // Found is total post count.
            String meta = JObject.optString("meta");
            int found = JObject.optInt("found");

            postID = new ArrayList<>();

            //If there are more then 100, which there always will unless something
            // catastrophic happens then set up the newURL.
            if (found > 100) {
                JSONObject metaLink = new JSONObject(meta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                Log.d("The Jones Theory", newURL);
            }

            // Loop through the posts and add the post ID to the array.
            // The posts is still from the original call.
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                postID.add(post.optString("ID"));
                count++;
            }

            //Now this logic is in charge of loading the next pages
            // until all posts are loaded into the array.
            while (count != found) {
                Request newRequest = new Request.Builder().url(newURL).build();
                Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
                if (!newResponse.isSuccessful())
                    throw new IOException();

                JSONObject nJObject = new JSONObject(newResponse.body().string());
                JSONArray nPosts = nJObject.optJSONArray("posts");
                String nMeta = nJObject.optString("meta");
                int newFound = nJObject.optInt("found");

                if (newFound > 100) {
                    JSONObject metaLink = new JSONObject(nMeta);
                    String nextValue = metaLink.optString("next_page");
                    newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                }
                for (int i = 0; i < nPosts.length(); i++) {
                    JSONObject post = nPosts.optJSONObject(i);
                    postID.add(post.optString("ID"));
                    count++;
                }
            }
            Collections.reverse(postID);
            download(postID);
            Log.d("The Jones Theory",
                    "getPostAll - Downloading = " + SharedPrefs.getInstance().isDownloading());
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

License:Apache License

private void getPostMissing() {
    notificationService();// ww w . j  a v a2  s .c  o  m
    SharedPrefs.getInstance().setDownloading(true);
    DatabaseManager databaseManager = new DatabaseManager(this);
    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";
    Request request = new Request.Builder().url(firstUrl).build();
    int count = 0;

    try {

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();

        //Take the response and parse the JSON
        JSONObject JObject = new JSONObject(response.body().string());
        JSONArray posts = JObject.optJSONArray("posts");

        //Store the data into the two objects, meta gets the next page later on.
        // Found is total post count.
        String meta = JObject.optString("meta");
        int found = JObject.optInt("found");

        postID = new ArrayList<>();

        //If there are more then 100, which there always will unless something
        // catastrophic happens then set up the newURL.
        if (found > 100) {
            JSONObject metaLink = new JSONObject(meta);
            String nextValue = metaLink.optString("next_page");
            newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
        }

        // Loop through the posts and add the post ID to the array.
        // The posts is still from the original call.
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            if (!databaseManager.idExists(post.optString("ID"))) {
                postID.add(post.optString("ID"));
            }
            count++;
        }

        //Now this logic is in charge of loading the next pages
        // until all posts are loaded into the array.
        while (count != found) {
            Request newRequest = new Request.Builder().url(newURL).build();
            Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
            if (!newResponse.isSuccessful())
                throw new IOException();

            JSONObject nJObject = new JSONObject(newResponse.body().string());
            JSONArray nPosts = nJObject.optJSONArray("posts");
            String nMeta = nJObject.optString("meta");
            int newFound = nJObject.optInt("found");

            if (newFound > 100) {
                JSONObject metaLink = new JSONObject(nMeta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");

            }

            for (int i = 0; i < nPosts.length(); i++) {
                JSONObject post = nPosts.optJSONObject(i);
                if (!databaseManager.idExists(post.optString("ID"))) {
                    postID.add(post.optString("ID"));
                }
                count++;
            }
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
    Collections.reverse(postID);
    download(postID);
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

License:Apache License

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {/*from ww w  .j a v  a  2  s . co m*/
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:net.protyposis.android.mediaplayer.dash.DashMediaExtractor.java

License:Open Source License

/**
 * Blocking download of a segment./*  w w  w  .  j a v a  2s .co  m*/
 */
private CachedSegment downloadFile(Integer segmentNr) throws IOException {
    // At the first call, download the initialization segments, and reuse them later.
    if (mInitSegments.isEmpty()) {
        for (Representation representation : mAdaptationSet.representations) {
            Request request = buildSegmentRequest(representation.initSegment);
            long startTime = SystemClock.elapsedRealtime();
            Response response = mHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("sync dl error @ init segment: " + response.code() + " "
                        + response.message() + " " + request.url().toString());
            }
            ByteString segmentData = response.body().source().readByteString();
            mInitSegments.put(representation, segmentData);
            mAdaptationLogic.reportSegmentDownload(mAdaptationSet, representation,
                    representation.segments.get(segmentNr), segmentData.size(),
                    SystemClock.elapsedRealtime() - startTime);
            Log.d(TAG, "init " + representation.initSegment.toString());
        }
    }

    Segment segment = mRepresentation.segments.get(segmentNr);
    Request request = buildSegmentRequest(segment);
    long startTime = SystemClock.elapsedRealtime();
    Response response = mHttpClient.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("sync dl error @ segment " + segmentNr + ": " + response.code() + " "
                + response.message() + " " + request.url().toString());
    }
    byte[] segmentData = response.body().bytes();
    mAdaptationLogic.reportSegmentDownload(mAdaptationSet, mRepresentation, segment, segmentData.length,
            SystemClock.elapsedRealtime() - startTime);
    CachedSegment cachedSegment = new CachedSegment(segmentNr, segment, mRepresentation);
    handleSegment(segmentData, cachedSegment);
    Log.d(TAG, "sync dl " + segmentNr + " " + segment.toString() + " -> " + cachedSegment.file.getPath());

    return cachedSegment;
}

From source file:net.protyposis.android.mediaplayer.dash.DashParser.java

License:Open Source License

/**
 * Parses an MPD XML file. This needs to be executed off the main thread, else a
 * NetworkOnMainThreadException gets thrown.
 * @param source the URl of an MPD XML file
 * @return a MPD object//from   w  w w .ja  v a  2  s.c o  m
 * @throws android.os.NetworkOnMainThreadException if executed on the main thread
 */
public MPD parse(UriSource source) throws DashParserException {
    MPD mpd = null;
    OkHttpClient httpClient = new OkHttpClient();

    Headers.Builder headers = new Headers.Builder();
    if (source.getHeaders() != null && !source.getHeaders().isEmpty()) {
        for (String name : source.getHeaders().keySet()) {
            headers.add(name, source.getHeaders().get(name));
        }
    }

    Uri uri = source.getUri();

    Request.Builder request = new Request.Builder().url(uri.toString()).headers(headers.build());

    try {
        Response response = httpClient.newCall(request.build()).execute();
        if (!response.isSuccessful()) {
            throw new IOException("error requesting the MPD");
        }

        // Determine this MPD's default BaseURL by removing the last path segment (which is the MPD file)
        Uri baseUrl = Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/") + 1));

        // Get the current datetime from the server for live stream time syncing
        serverDate = response.headers().getDate("Date");

        // Parse the MPD file
        mpd = parse(response.body().byteStream(), baseUrl);
    } catch (IOException e) {
        Log.e(TAG, "error downloading the MPD", e);
        throw new DashParserException("error downloading the MPD", e);
    } catch (XmlPullParserException e) {
        Log.e(TAG, "error parsing the MPD", e);
        throw new DashParserException("error parsing the MPD", e);
    }

    return mpd;
}

From source file:net.simonvt.cathode.api.RetryingInterceptor.java

License:Apache License

private Response proceed(Chain chain, Request request, int retryCount) throws IOException {
    if (retryCount > 0 && retryDelay > 0) {
        Timber.d("Retrying request in %d milliseconds", retryDelay);
        try {//from  w w  w .  j  a  v a 2 s  . c  om
            Thread.sleep(retryDelay);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
    Response response;
    try {
        response = chain.proceed(request);
        if (!response.isSuccessful()) {
            if (retryCount < maxRetryCount) {
                response = proceed(chain, request, retryCount + 1);
            }
        }
    } catch (IOException e) {
        if (retryCount < maxRetryCount) {
            response = proceed(chain, request, retryCount + 1);
        } else {
            throw e;
        }
    }

    return response;
}

From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java

License:Open Source License

public <S> S request(Class<S> service, String username, String password) {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(60, TimeUnit.SECONDS);
    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.interceptors().add(new AuthenticationInterceptor(username, password));
    client.interceptors().add(new Interceptor() {
        @Override//from w  ww .  j  av  a  2  s.  com
        public Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Request request = chain.request();
            Response response = chain.proceed(request);

            int retryCount = 0;
            while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) {
                Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
                response = chain.proceed(request);
                retryCount++;
            }
            if (!response.isSuccessful())
                log.error(request.urlString() + " request failed.");

            return response;
        }
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new TaskboardJacksonModule());
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl())
            .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build();

    return retrofit.create(service);
}

From source file:org.apache.heron.scheduler.kubernetes.AppsV1beta1Controller.java

License:Apache License

@Override
boolean submit(PackingPlan packingPlan) {
    final String topologyName = getTopologyName();
    if (!topologyName.equals(topologyName.toLowerCase())) {
        throw new TopologySubmissionException("K8S scheduler does not allow upper case topologies.");
    }/*w  w w .  jav  a  2 s  .  co  m*/

    final Resource containerResource = getContainerResource(packingPlan);

    // find the max number of instances in a container so we can open
    // enough ports if remote debugging is enabled.
    int numberOfInstances = 0;
    for (PackingPlan.ContainerPlan containerPlan : packingPlan.getContainers()) {
        numberOfInstances = Math.max(numberOfInstances, containerPlan.getInstances().size());
    }
    final V1beta1StatefulSet statefulSet = createStatefulSet(containerResource, numberOfInstances);

    try {
        final Response response = client
                .createNamespacedStatefulSetCall(getNamespace(), statefulSet, null, null, null).execute();
        if (!response.isSuccessful()) {
            LOG.log(Level.SEVERE, "Error creating topology message: " + response.message());
            KubernetesUtils.logResponseBodyIfPresent(LOG, response);
            // construct a message based on the k8s API server response
            throw new TopologySubmissionException(KubernetesUtils.errorMessageFromResponse(response));
        }
    } catch (IOException | ApiException e) {
        KubernetesUtils.logExceptionWithDetails(LOG, "Error creating topology", e);
        throw new TopologySubmissionException(e.getMessage());
    }

    return true;
}