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:org.graylog2.alarmcallbacks.HTTPAlarmCallback.java

License:Open Source License

@Override
public void call(final Stream stream, final AlertCondition.CheckResult result) throws AlarmCallbackException {
    final Map<String, Object> event = Maps.newHashMap();
    event.put("stream", stream);
    event.put("check_result", result);

    final Response r;
    try {//  w w w  . j a v a  2s  .  co m
        final byte[] body = objectMapper.writeValueAsBytes(event);
        final URL url = new URL(configuration.getString(CK_URL));
        final Request request = new Request.Builder().url(url).post(RequestBody.create(CONTENT_TYPE, body))
                .build();
        r = httpClient.newCall(request).execute();
    } catch (JsonProcessingException e) {
        throw new AlarmCallbackException("Unable to serialize alarm", e);
    } catch (MalformedURLException e) {
        throw new AlarmCallbackException("Malformed URL", e);
    } catch (IOException e) {
        throw new AlarmCallbackException(e.getMessage(), e);
    }

    if (!r.isSuccessful()) {
        throw new AlarmCallbackException("Expected successful HTTP response [2xx] but got [" + r.code() + "].");
    }
}

From source file:org.graylog2.initializers.IndexerSetupService.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    Tools.silenceUncaughtExceptionsInThisThread();

    LOG.debug("Starting indexer");
    try {//  ww w  .j  a  v  a 2 s . com
        node.start();

        final Client client = node.client();
        try {
            /* try to determine the cluster health. if this times out we could not connect and try to determine if there's
               anything listening at all. if that happens this usually has these reasons:
            1. cluster.name is different
            2. network.publish_host is not reachable
            3. wrong address configured
            4. multicast in use but broken in this environment
               we handle a red cluster state differently because if we can get that result it means the cluster itself
               is reachable, which is a completely different problem from not being able to join at all.
             */
            final ClusterHealthRequest atLeastRed = new ClusterHealthRequest()
                    .waitForStatus(ClusterHealthStatus.RED);
            final ClusterHealthResponse health = client.admin().cluster().health(atLeastRed)
                    .actionGet(configuration.getClusterDiscoveryTimeout(), MILLISECONDS);
            // we don't get here if we couldn't join the cluster. just check for red cluster state
            if (ClusterHealthStatus.RED.equals(health.getStatus())) {
                UI.exitHardWithWall("The Elasticsearch cluster state is RED which means shards are unassigned. "
                        + "This usually indicates a crashed and corrupt cluster and needs to be investigated. Graylog will shut down.",
                        "http://docs.graylog.org/en/1.0/pages/configuring_es.html");

            }
        } catch (ElasticsearchTimeoutException e) {
            final String hosts = node.settings().get("discovery.zen.ping.unicast.hosts");

            if (!isNullOrEmpty(hosts)) {
                final Iterable<String> hostList = Splitter.on(',').omitEmptyStrings().trimResults()
                        .split(hosts);

                for (String host : hostList) {
                    final URI esUri = URI
                            .create("http://" + HostAndPort.fromString(host).getHostText() + ":9200/");

                    LOG.info("Checking Elasticsearch HTTP API at {}", esUri);
                    try {
                        // Try the HTTP API endpoint
                        final Request request = new Request.Builder().get()
                                .url(esUri.resolve("/_nodes").toString()).build();
                        final Response response = httpClient.newCall(request).execute();

                        if (response.isSuccessful()) {
                            final JsonNode resultTree = objectMapper.readTree(response.body().byteStream());
                            final JsonNode nodesList = resultTree.get("nodes");

                            if (!configuration.isDisableVersionCheck()) {
                                final Iterator<String> nodes = nodesList.fieldNames();
                                while (nodes.hasNext()) {
                                    final String id = nodes.next();
                                    final Version clusterVersion = Version
                                            .fromString(nodesList.get(id).get("version").textValue());

                                    checkClusterVersion(clusterVersion);
                                }
                            }

                            final String clusterName = resultTree.get("cluster_name").textValue();
                            checkClusterName(clusterName);
                        } else {
                            LOG.error("Could not connect to Elasticsearch at " + esUri + ". Is it running?");
                        }
                    } catch (IOException ioException) {
                        LOG.error("Could not connect to Elasticsearch.", ioException);
                    }
                }
            }

            UI.exitHardWithWall(
                    "Could not successfully connect to Elasticsearch, if you use multicast check that it is working in your network"
                            + " and that Elasticsearch is running properly and is reachable. Also check that the cluster.name setting is correct.",
                    "http://docs.graylog.org/en/1.0/pages/configuring_es.html");
        }
    } catch (Exception e) {
        bufferSynchronizerService.setIndexerUnavailable();
        throw e;
    }
}

From source file:org.graylog2.inputs.transports.HttpPollTransport.java

License:Open Source License

@Override
public void doLaunch(final MessageInput input) throws MisfireException {
    serverStatus.awaitRunning(new Runnable() {
        @Override/*w w  w.j  a  va  2s .  c o  m*/
        public void run() {
            lifecycleStateChange(Lifecycle.RUNNING);
        }
    });

    // listen for lifecycle changes
    serverEventBus.register(this);

    final Map<String, String> headers = parseHeaders(configuration.getString(CK_HEADERS));

    // figure out a reasonable remote address
    final String url = configuration.getString(CK_URL);
    final InetSocketAddress remoteAddress;
    InetSocketAddress remoteAddress1;
    try {
        final URL url1 = new URL(url);
        final int port = url1.getPort();
        remoteAddress1 = new InetSocketAddress(url1.getHost(), port != -1 ? port : 80);
    } catch (MalformedURLException e) {
        remoteAddress1 = null;
    }
    remoteAddress = remoteAddress1;

    final Runnable task = new Runnable() {
        @Override
        public void run() {
            if (paused) {
                LOG.debug("Message processing paused, not polling HTTP resource {}.", url);
                return;
            }
            if (isThrottled()) {
                // this transport won't block, but we can simply skip this iteration
                LOG.debug("Not polling HTTP resource {} because we are throttled.", url);
            }

            final Request.Builder requestBuilder = new Request.Builder().get().url(url)
                    .headers(Headers.of(headers));

            try {
                final Response r = httpClient.newCall(requestBuilder.build()).execute();

                if (!r.isSuccessful()) {
                    throw new RuntimeException("Expected successful HTTP status code [2xx], got " + r.code());
                }

                input.processRawMessage(new RawMessage(r.body().bytes(), remoteAddress));
            } catch (IOException e) {
                LOG.error("Could not fetch HTTP resource at " + url, e);
            }
        }
    };

    scheduledFuture = scheduler.scheduleAtFixedRate(task, 0, configuration.getInt(CK_INTERVAL),
            TimeUnit.valueOf(configuration.getString(CK_TIMEUNIT)));
}

From source file:org.graylog2.radio.cluster.InputService.java

License:Open Source License

public List<PersistedInputsResponse> getPersistedInputs() throws IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs")
            .build(nodeId.toString());/*from w ww .  ja  v  a  2 s.c  o m*/

    final Request request = new Request.Builder().header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON).get()
            .url(uri.toString()).build();

    final Response r = httpclient.newCall(request).execute();
    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected successful HTTP response [2xx] for list of persisted input but got [" + r.code()
                        + "].");
    }

    final PersistedInputsSummaryResponse persistedInputsResponse = mapper.readValue(r.body().byteStream(),
            PersistedInputsSummaryResponse.class);

    return persistedInputsResponse.inputs();
}

From source file:org.graylog2.radio.cluster.InputService.java

License:Open Source License

public RegisterInputResponse registerInCluster(MessageInput input)
        throws ExecutionException, InterruptedException, IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs")
            .build(nodeId.toString());//from www. j ava  2s  .  c  o m

    final RegisterInputRequest rir = RegisterInputRequest.create(input.getId(), input.getTitle(),
            input.getType(), input.getConfiguration().getSource(), nodeId.toString(), input.getCreatorUserId());

    final Request request = new Request.Builder()
            .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), mapper.writeValueAsBytes(rir)))
            .url(uri.toString()).build();

    final Response r = httpclient.newCall(request).execute();
    final RegisterInputResponse registerInputResponse = mapper.readValue(r.body().byteStream(),
            RegisterInputResponse.class);

    // Set the ID that was generated in the server as persist ID of this input.
    input.setPersistId(registerInputResponse.persistId());

    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected HTTP response [2xx] for input registration but got [" + r.code() + "].");
    }

    return registerInputResponse;
}

From source file:org.graylog2.radio.cluster.InputService.java

License:Open Source License

public void unregisterInCluster(MessageInput input)
        throws ExecutionException, InterruptedException, IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs/{inputId}")
            .build(nodeId.toString(), input.getPersistId());

    final Request request = new Request.Builder().header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON).delete()
            .url(uri.toString()).build();

    final Response r = httpclient.newCall(request).execute();
    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected HTTP response [2xx] for input unregistration but got [" + r.code() + "].");
    }//  w w  w  .  j a  va 2  s  .c  o m
}

From source file:org.graylog2.radio.cluster.Ping.java

License:Open Source License

public void ping() throws IOException {
    final PingRequest pingRequest = PingRequest.create(ourUri.toString());

    final URI uri = serverUri.resolve("/system/radios/" + nodeId + "/ping");
    final Request request = new Request.Builder().url(uri.toURL())
            .put(RequestBody.create(CONTENT_TYPE, objectMapper.writeValueAsBytes(pingRequest))).build();

    final Response r = httpClient.newCall(request).execute();

    // fail on a non-ok status
    if (!r.isSuccessful()) {
        throw new RuntimeException("Expected successful HTTP response [2xx] but got [" + r.code()
                + "]. Request was " + request.urlString());
    }//www. j  av a 2s  .  co m
}

From source file:org.hawkular.commons.rest.status.itest.StatusEndpointITest.java

License:Apache License

@Test(groups = { GROUP })
public void testStatusEndpoint() throws IOException, InterruptedException {

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().addHeader("Accept", "application/json").url(statusUrl).build();

    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        String foundBody = response.body().string();

        /* see src/test/resources/rest-status/MANIFEST.MF */
        String expected = "{\"Implementation-Version\":\"1.2.3.4\","//
                + "\"Built-From-Git-SHA1\":\"cofeebabe\","//
                + "\"testKey1\":\"testValue1\"}";
        Assert.assertEquals(foundBody, expected);
    } else {/*from   www  . j a  va2 s . c om*/
        Assert.fail("Could not get [" + statusUrl + "]: " + response.code() + " " + response.message());
    }

}

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

License:Open Source License

public List<Show> searchShows(String query) {

    try {/*from ww  w . j  a v a 2s  .  co 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 {/*www.  j  ava 2 s .  c om*/
        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;
    }
}