Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:org.hawkular.integration.test.HystrixCommandsITest.java

License:Apache License

@Test
public void testComplexScenario() throws Exception {
    this.di = new Weld().initialize();
    String originalUrl = "www.redhat.com";
    String newUrl = "www.hawkular.org";

    Observable<String> getTenant = Observable.<String>defer(() -> {
        try {//from  ww w .jav a  2s.  co m
            Response response = client
                    .newCall(newAuthRequest().url(baseURI + "/hawkular/inventory/tenant").build()).execute();
            Assert.assertEquals(200, response.code());
            Tenant tenant = mapper.readValue(response.body().string(), Tenant.class);
            // wait for the automagic in the inventory
            return Observable.just(tenant.getId()).delay(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    // using the flatMap for chaining the events and assert functions as testing by side-effects (it's not pure
    // functional approach, but we need to check also the intermediate results, perhaps the .all/.filter could do
    // the trick)

    // get tenant id

    Observable<String> bigObs = getTenant.flatMap((String tenantId) -> {
        return di
                .select(CreateUrlCommand.class, CreateCommandLiteral.get(),
                        Initialized.withValues(originalUrl, authHeader, tenantId))
                .get().toObservable()

                .flatMap((String location) -> {
                    Assert.assertNotNull(location);
                    Assert.assertNotEquals(location.trim().length(), 0);

                    String resId = location.substring(location.lastIndexOf("/") + 1);
                    Assert.assertNotEquals(resId.trim().length(), 0);
                    System.out.println("created url with id: " + resId);

                    // try to retrieve it
                    return getUrl(resId, tenantId).flatMap(url -> {
                        Assert.assertTrue(url.contains(originalUrl));

                        // change the url
                        return updateUrl(resId, newUrl, tenantId);
                    })

                            // try to retrieve it
                            .flatMap(foo -> getUrl(resId, tenantId)).flatMap(url -> {
                                Assert.assertTrue(url.contains(newUrl));

                                // delete the url
                                return deleteUrl(resId, tenantId);
                            }).flatMap(foo -> {
                                // get all urls
                                return getUrl(null, tenantId);
                            });
                });
    }).doOnError(e -> {
        System.out.println(e.getMessage());
        Assert.fail("fail: " + e.getMessage());
    });

    System.out.println("observable pipes initialized");

    // wait for the pipe
    String urlJsonList = bigObs.toBlocking().first();

    // check that nothing is there
    Assert.assertEquals("[ ]", urlJsonList);
}

From source file:org.hawkular.integration.test.Scenario1ITest.java

License:Apache License

@Test
public void testScenario() throws Throwable {
    Persona persona = getWithRetries("/hawkular/accounts/personas/current", HawkularUser.class, 10, 2000);
    String tenantId = persona.getIdAsUUID().toString();
    Assert.assertTrue("Cannot get the current tenant id.", tenantId != null && !tenantId.trim().isEmpty());

    /* assert the test environment exists */
    /* There is a race condition when WildFly agent is enabled:
       both this test and Agent trigger the autocreation of test entities simultaneously,
       and one of them may get only a partially initialized state.
       That is why we do several delayed attempts do perform the first request.
     *//*from   w  ww .j ava  2  s  .c om*/
    String path = "/hawkular/inventory/environments/" + environmentId;
    Environment env = getWithRetries(path, Environment.class, 10, 2000);
    Assert.assertEquals("Unable to get the '" + environmentId + "' environment.", environmentId, env.getId());

    /* assert the URL resource type exists */
    path = "/hawkular/inventory/resourceTypes/" + urlTypeId;
    ResourceType resourceType = getWithRetries(path, ResourceType.class, 10, 2000);
    Assert.assertEquals("Unable to get the '" + urlTypeId + "' resource type.", urlTypeId,
            resourceType.getId());

    /* assert the metric types exist */
    path = "/hawkular/inventory/metricTypes/" + statusCodeTypeId;
    MetricType statusCodeType = getWithRetries(path, MetricType.class, 10, 2000);
    Assert.assertEquals("Unable to get the '" + statusCodeTypeId + "' metric type.", statusCodeTypeId,
            statusCodeType.getId());

    path = "/hawkular/inventory/metricTypes/" + durationTypeId;
    MetricType durationType = getWithRetries(path, MetricType.class, 10, 2000);
    Assert.assertEquals("Unable to get the '" + durationTypeId + "' metric type.", durationTypeId,
            durationType.getId());

    /* create a URL */
    String resourceId = UUID.randomUUID().toString();
    Resource.Blueprint newResource = Resource.Blueprint.builder().withId(resourceId)
            .withResourceTypePath(urlTypePath).withProperty("url", "http://hawkular.org").build();
    postNew("/hawkular/inventory/" + environmentId + "/resources", newResource);
    pathsToDelete.add("/hawkular/inventory/" + environmentId + "/resources/" + resourceId);

    /* create the metrics */
    String statusCodeId = UUID.randomUUID().toString();
    Metric.Blueprint codeMetric = Metric.Blueprint.builder().withMetricTypePath(statusCodeTypePath)
            .withId(statusCodeId).build();
    postNew("/hawkular/inventory/" + environmentId + "/metrics", codeMetric);
    pathsToDelete.add("/hawkular/inventory/" + environmentId + "/metrics/" + statusCodeId);

    String durationId = UUID.randomUUID().toString();
    Metric.Blueprint durationMetric = Metric.Blueprint.builder().withMetricTypePath(durationTypePath)
            .withId(durationId).build();
    postNew("/hawkular/inventory/" + environmentId + "/metrics", durationMetric);
    pathsToDelete.add("/hawkular/inventory/" + environmentId + "/metrics/" + durationId);

    /* assign metrics to the resource */
    Response response = post("/hawkular/inventory/" + environmentId + "/resources/" + resourceId + "/metrics",
            "[\"/e;" + environmentId + "/m;" + statusCodeId + "\", \"/e;" + environmentId + "/m;" + durationId
                    + "\"]");
    Assert.assertEquals("Response msg: " + response.body().string(), 204, response.code());

    /* Pinger should start pinging now but we do not want to wait */

    // 9 simulate ping + response - metrics for ~ the last 30 minutes

    /* Wait till metrics gets initialized */
    path = "/hawkular/metrics/status";
    int delay = 1000;
    int attemptCount = 30;
    String metricsServiceStatus = null;
    for (int i = 0; i < 30; i++) {
        response = client.newCall(newAuthRequest().url(baseURI + path).build()).execute();
        if (response.code() == 200) {
            String mStatusStr = response.body().string();
            Map<String, String> mStatusMap = mapper.readValue(mStatusStr, mapTypeRef);
            metricsServiceStatus = mStatusMap.get("MetricsService");
            if ("STARTED".equals(metricsServiceStatus)) {
                /* the service has started - we can leave the loop */
                break;
            }
        }
        System.out.println("'MetricsService' not ready yet, about to retry after " + delay + " ms");
        /* sleep one second */
        Thread.sleep(delay);
    }
    if (!"STARTED".equals(metricsServiceStatus)) {
        Assert.fail("MetricsService status still '" + metricsServiceStatus + "' after trying " + attemptCount
                + " times" + " with delay $delay ms.");
    }

    for (int i = -30; i < -3; i++) {
        postMetricValue(resourceId, statusCodeId, 100 + i, i);
        postMetricValue(resourceId, durationId, 200, i);
    }

    postMetricValue(resourceId, statusCodeId, 500, -2);
    postMetricValue(resourceId, statusCodeId, 404, -1);
    postMetricValue(resourceId, statusCodeId, 200, 0);
    postMetricValue(resourceId, statusCodeId, 42, 0);

    /* Get values for a chart - last 4h data */
    long end = System.currentTimeMillis();
    long start = end - 4 * 3600 * 1000;// 4h earlier
    path = "/hawkular/metrics/gauges/" + resourceId + "." + statusCodeId + "/data";
    String query = "?start=" + start + "&end=" + end;
    response = client.newCall(newAuthRequest().url(baseURI + path + query).build()).execute();
    String body = response.body().string();
    TypeReference<List<DataPoint<Double>>> dataPointListTypeRef = new TypeReference<List<DataPoint<Double>>>() {
    };
    List<DataPoint<Double>> statuses = mapper.readValue(body, dataPointListTypeRef);

    Assert.assertEquals(31, statuses.size());

    path = "/hawkular/metrics/gauges/" + resourceId + "." + durationId + "/data";
    query = "?start=" + start + "&end=" + end;
    response = client.newCall(newAuthRequest().url(baseURI + path + query).build()).execute();
    body = response.body().string();
    List<DataPoint<Double>> durations = mapper.readValue(body, dataPointListTypeRef);
    Assert.assertEquals(27, durations.size());

    /* TODO: define an alert */
    // response = postDeletable(path: "alerts/triggers/")

}

From source file:org.hawkular.integration.test.Scenario1ITest.java

License:Apache License

@AfterClass
static void cleanUp() throws IOException {
    /* Let's delete the entities one after another in the inverse order as we created them */
    for (int i = pathsToDelete.size() - 1; i >= 0; i--) {
        String path = pathsToDelete.get(i);
        Response response = client.newCall(newAuthRequest().url(baseURI + path).delete().build()).execute();
        Assert.assertEquals("Response msg: " + response.body().string(), 204, response.code());

        response = client.newCall(newAuthRequest().url(baseURI + path).build()).execute();
        Assert.assertEquals("Response msg: " + response.body().string(), 404, response.code());
    }/*w w  w  . j  ava 2  s .c  om*/
}

From source file:org.hawkular.integration.test.Scenario1ITest.java

License:Apache License

private void postMetricValue(String resourceId, String metricName, int value, int timeSkewMinutes)
        throws IOException {
    long now = System.currentTimeMillis();
    String tmp = resourceId + "." + metricName;

    long time = now + (timeSkewMinutes * 60 * 1000);

    String path = "/hawkular/metrics/gauges/" + tmp + "/data";
    String json = "[{timestamp: " + time + ", value: " + value + "}]";
    Request request = newAuthRequest().url(baseURI + path).post(RequestBody.create(MEDIA_TYPE_JSON, json))
            .build();//from  w w  w  .  ja v a  2  s  .  c o  m
    Response response = client.newCall(request).execute();
    Assert.assertEquals("Response msg: " + response.body().string(), 200, response.code());
}

From source file:org.hawkular.wildfly.agent.installer.AgentInstallerITest.java

License:Apache License

@Test(dependsOnMethods = { "datasourcesAddedToInventory" })
public void datasourceMetricsCollected() throws Throwable {
    String lastUrl = "";
    int second = 1000;
    int timeOutSeconds = 60;
    for (int i = 0; i < timeOutSeconds; i++) {
        Request request = newAuthRequest().url(baseMetricsUri + "/gauges").build();
        Response gaugesResponse = client.newCall(request).execute();

        if (gaugesResponse.code() == 200 && !gaugesResponse.body().string().isEmpty()) {
            for (String datasourceName : getDatasourceNames()) {
                String id = "MI~R~[" + wfFeedId + "/Local~/subsystem=datasources/data-source=" + datasourceName
                        + "]~MT~Datasource Pool Metrics~Available Count";
                id = URLEncoder.encode(id, "UTF-8");
                String url = baseMetricsUri + "/gauges/data?buckets=1&metrics=" + id;
                lastUrl = url;//from   ww w . ja va2  s.c  om
                //System.out.println("url = " + url);
                Response gaugeResponse = client.newCall(newAuthRequest().url(url).get().build()).execute();
                if (gaugeResponse.code() == 200 && !gaugeResponse.body().string().isEmpty()) {
                    /* this should be enough to prove that some metric was written successfully */
                    return;
                }
            }
        }
        Thread.sleep(second);
    }

    Assert.fail("Gauge still not available after [" + timeOutSeconds + "] seconds: [" + lastUrl + "]");

}

From source file:org.hawkular.wildfly.agent.installer.AgentInstallerStandaloneITest.java

License:Apache License

@Test(dependsOnMethods = { "datasourcesAddedToInventory" })
public void datasourceMetricsCollected() throws Throwable {
    String lastUrl = "";
    int second = 1000;
    int timeOutSeconds = 60;
    for (int i = 0; i < timeOutSeconds; i++) {
        Request request = newAuthRequest().url(baseMetricsUri + "/gauges").build();
        Response gaugesResponse = client.newCall(request).execute();

        if (gaugesResponse.code() == 200 && !gaugesResponse.body().string().isEmpty()) {
            for (String datasourceName : getDatasourceNames()) {
                String id = "MI~R~[" + wfClientConfig.getFeedId() + "/Local~/subsystem=datasources/data-source="
                        + datasourceName + "]~MT~Datasource Pool Metrics~Available Count";
                id = Util.urlEncodeQuery(id);
                String url = baseMetricsUri + "/gauges/stats?buckets=1&metrics=" + id;
                lastUrl = url;/* ww  w.  j  av a 2s  .co  m*/
                //System.out.println("url = " + url);
                Response gaugeResponse = client.newCall(newAuthRequest().url(url).get().build()).execute();
                if (gaugeResponse.code() == 200 && !gaugeResponse.body().string().isEmpty()) {
                    /* this should be enough to prove that some metric was written successfully */
                    return;
                }
            }
        }
        Thread.sleep(second);
    }

    Assert.fail("Gauge still not gathered after [" + timeOutSeconds + "] seconds: [" + lastUrl + "]");
}

From source file:org.hawkular.wildfly.agent.installer.AgentInstallerStandaloneITest.java

License:Apache License

@Test(dependsOnMethods = { "datasourcesAddedToInventory" }, enabled = true)
public void serverAvailCollected() throws Throwable {
    String lastUrl = "";
    int second = 1000;
    int timeOutSeconds = 60;

    for (int i = 0; i < timeOutSeconds; i++) {
        Request request = newAuthRequest().url(baseMetricsUri + "/availability").build();
        Response availabilityResponse = client.newCall(request).execute();

        if (availabilityResponse.code() == 200 && !availabilityResponse.body().string().isEmpty()) {
            String id = "AI~R~[" + wfClientConfig.getFeedId()
                    + "/Local~~]~AT~Server Availability~Server Availability";
            id = Util.urlEncode(id);
            String url = baseMetricsUri + "/availability/" + id + "/raw";
            //System.out.println("url = " + url);
            availabilityResponse = client.newCall(newAuthRequest().url(url).get().build()).execute();
            if (availabilityResponse.code() == 200 && !availabilityResponse.body().string().isEmpty()) {
                /* this should be enough to prove that some metric was written successfully */
                return;
            } else {
                System.out.println("code = " + availabilityResponse.code());
            }/*from w w  w.  j  a va2s  .c o m*/
        }
        Thread.sleep(second);
    }

    Assert.fail("Availability still not gathered after [" + timeOutSeconds + "] seconds: [" + lastUrl + "]");

}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

License:Apache License

protected String getWithRetries(String url, int attemptCount, long attemptDelay) throws Throwable {
    Throwable e = null;/*from  ww w. j a v a  2 s  .c  o m*/
    for (int i = 0; i < attemptCount; i++) {
        try {
            Request request = newAuthRequest().url(url).build();
            Response response = client.newCall(request).execute();
            System.out.println("Got code " + response.code() + " and message [" + response.message()
                    + "] retries: " + url);
            AssertJUnit.assertEquals(200, response.code());
            System.out.println("Got after " + (i + 1) + " retries: " + url);
            return response.body().string();
        } catch (Throwable t) {
            /* some initial attempts may fail */
            e = t;
        }
        System.out.println("URL [" + url + "] not ready yet on " + (i + 1) + " of " + attemptCount
                + " attempts, about to retry after " + attemptDelay + " ms");
        Thread.sleep(attemptDelay);
    }
    if (e != null) {
        throw e;
    } else {
        throw new AssertionError("Could not get [" + url + "]");
    }
}

From source file:org.jamienicol.episodes.tvdb.Client.java

License:Open Source License

public List<Show> searchShows(String query) {

    try {/*w  w w  . j a  va  2 s. c o  m*/
        final String escapedQuery = URLEncoder.encode(query, "UTF-8");
        final String url = String.format("%s/GetSeries.php?seriesname=%s", baseUrl, escapedQuery);
        Log.d(TAG, String.format("Sending request to %s", url));

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

        final Response response = http.newCall(request).execute();

        Log.d(TAG, String.format("Received response %d: %s", response.code(), response.message()));

        if (response.isSuccessful()) {
            final SearchShowsParser parser = new SearchShowsParser();

            return parser.parse(response.body().byteStream());
        } else {
            return null;
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}

From source file:org.jamienicol.episodes.tvdb.Client.java

License:Open Source License

public Show getShow(int id) {
    try {/*from ww  w  .  j  ava  2s .  c  o m*/
        final String url = String.format(Locale.US, "%s/%s/series/%d/all/en.xml", baseUrl, apiKey, id);
        Log.d(TAG, String.format("Sending request to %s", url));

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

        final Response response = http.newCall(request).execute();

        Log.d(TAG, String.format("Received response %d: %s", response.code(), response.message()));

        if (response.isSuccessful()) {
            final GetShowParser parser = new GetShowParser();

            return parser.parse(response.body().byteStream());
        } else {
            return null;
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}