List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
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 ww w. j a v a 2s . 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());/* www. j av a2s . co 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() + "]."); }//from w w w. j a va 2 s . c om }
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()); }/* ww w .ja v a2 s . com*/ }
From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java
License:Apache License
@Override public void run() { Request request = null;/*from w ww . j ava 2s.co m*/ try { String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier(); request = new Request.Builder().url(uri).addHeader("Accept", JSON_MEDIA_TYPE.toString()).get().build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { if (e instanceof ConnectException) { LOG.warn("Reading job failed: target " + baseuri + " seems down"); } else { LOG.warn("Reading job failed: " + e); } } @Override public void onResponse(Response response) throws IOException { if (response.code() == 204) { return; // No content, nothing to do } String content = response.body().string(); OpsRequest map = Util.fromJson(content, OpsRequest.class); String action = map.getAction(); String operationId = map.getId(); String tenantId = map.getTenantId(); // "[Local~/deployment=hawkular-avail-creator.war]" String resId = map.getResourceId(); resId = resId.substring(resId.indexOf("~/") + 2); if (resId.endsWith("]")) { resId = resId.substring(0, resId.length() - 1); } Address address = Address.parse(resId); LOG.debug("Executing " + address + "/:" + action); ModelNode mrequest = JBossASClient.createRequest(action, address); try { ModelNode result = asClient.execute(mrequest); OpsResult outcome = toOutcome(result); LOG.debug("Outcome " + outcome); submitResult(operationId, tenantId, outcome); } catch (Exception e) { throw new IOException(e); } } }); } catch (Throwable t) { LOG.warn("Error: " + t.getMessage()); } }
From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java
License:Apache License
private void submitResult(String operationId, String tenantId, OpsResult result) throws Exception { Request request;//ww w .j a v a 2 s.com String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier() + "/" + operationId; String json = Util.toJson(result); RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json); request = new Request.Builder().url(uri).post(body).addHeader("Hawkular-Tenant", tenantId).build(); // Asynchronous POST httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { LOG.warn("Sending of response failed: " + e); } @Override public void onResponse(Response response) throws IOException { if (response.code() != 200) { LOG.warn("Send failed : " + response.message()); } } }); }
From source file:org.hawkular.agent.monitor.service.MonitorService.java
License:Apache License
private void waitForHawkularServer() throws Exception { OkHttpClient httpclient = this.httpClientBuilder.getHttpClient(); String statusUrl = Util.getContextUrlString(configuration.getStorageAdapter().getUrl(), configuration.getStorageAdapter().getMetricsContext()).append("status").toString(); Request request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null); int counter = 0; while (true) { Response response = null; try {//from w w w . j a v a2 s.c o m response = httpclient.newCall(request).execute(); if (response.code() != 200) { log.debugf("Hawkular Metrics is not ready yet: %d/%s", response.code(), response.message()); } else { log.debugf("Hawkular Metrics is ready: %s", response.body().string()); break; } } catch (Exception e) { log.debugf("Hawkular Metrics is not ready yet: %s", e.toString()); } finally { if (response != null) { response.body().close(); } } Thread.sleep(5000L); counter++; if (counter % 12 == 0) { log.warnConnectionDelayed(counter, "metrics", statusUrl); } } if (this.configuration.getStorageAdapter().getType() == StorageReportTo.HAWKULAR) { statusUrl = Util.getContextUrlString(configuration.getStorageAdapter().getUrl(), configuration.getStorageAdapter().getInventoryContext()).append("status").toString(); request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null); counter = 0; while (true) { Response response = null; try { response = httpclient.newCall(request).execute(); if (response.code() != 200) { log.debugf("Hawkular Inventory is not ready yet: %d/%s", response.code(), response.message()); } else { log.debugf("Hawkular Inventory is ready: %s", response.body().string()); break; } } catch (Exception e) { log.debugf("Hawkular Inventory is not ready yet: %s", e.toString()); } finally { if (response != null) { response.body().close(); } } Thread.sleep(5000L); counter++; if (counter % 5 == 0) { log.warnConnectionDelayed(counter, "inventory", statusUrl); } } } }
From source file:org.hawkular.agent.monitor.service.MonitorService.java
License:Apache License
/** * Registers the feed with the Hawkular system under the given tenant. * Note, it is OK to re-register the same feed/tenant combinations. * * If retryMillis > 0 then this will not return until the feed is properly registered. * If the Hawkular server is not up, this could mean we are stuck here for a long time. * * @param tenantId the feed is registered under the given tenantId * @param retryMillis if >0 the amount of millis to elapse before retrying * @throws Exception if failed to register feed *//* ww w . ja va2 s . c o m*/ public void registerFeed(String tenantId, int retryMillis) throws Exception { // get the payload in JSON format Feed.Blueprint feedPojo = new Feed.Blueprint(this.feedId, null); String jsonPayload = Util.toJson(feedPojo); // build the REST URL... // start with the protocol, host, and port, plus context StringBuilder url = Util.getContextUrlString(configuration.getStorageAdapter().getUrl(), configuration.getStorageAdapter().getInventoryContext()); // rest of the URL says we want the feeds API url.append("entity/feed"); // now send the REST requests - one for each tenant to register OkHttpClient httpclient = this.httpClientBuilder.getHttpClient(); Map<String, String> header = Collections.singletonMap("Hawkular-Tenant", tenantId); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), header, jsonPayload); boolean keepRetrying = (retryMillis > 0); do { try { // note that we retry if newCall.execute throws an exception (assuming we were told to retry) Response httpResponse = httpclient.newCall(request).execute(); try { // HTTP status of 201 means success; 409 means it already exists, anything else is an error if (httpResponse.code() == 201) { keepRetrying = false; final String feedObjectFromServer = httpResponse.body().string(); final Feed feed = Util.fromJson(feedObjectFromServer, Feed.class); if (this.feedId.equals(feed.getId())) { log.infoUsingFeedId(feed.getId(), tenantId); } else { // do not keep retrying - this is a bad error; we need to abort log.errorUnwantedFeedId(feed.getId(), this.feedId, tenantId); throw new Exception(String.format("Received unwanted feed [%s]", feed.getId())); } } else if (httpResponse.code() == 409) { keepRetrying = false; log.infoFeedIdAlreadyRegistered(this.feedId, tenantId); } else if (httpResponse.code() == 404) { // the server is probably just starting to come up - wait for it if we were told to retry keepRetrying = (retryMillis > 0); throw new Exception(String.format("Is the Hawkular Server booting up? (%d=%s)", httpResponse.code(), httpResponse.message())); } else { // futile to keep retrying and getting the same 500 or whatever error keepRetrying = false; throw new Exception(String.format("status-code=[%d], reason=[%s]", httpResponse.code(), httpResponse.message())); } } finally { httpResponse.body().close(); } } catch (Exception e) { log.warnCannotRegisterFeed(this.feedId, tenantId, request.urlString(), e.toString()); if (keepRetrying) { Thread.sleep(retryMillis); } else { throw e; } } } while (keepRetrying); }
From source file:org.hawkular.agent.monitor.storage.MetricsOnlyStorageAdapter.java
License:Apache License
@Override public void store(MetricDataPayloadBuilder payloadBuilder) { String jsonPayload = "?"; try {//from ww w .j a va 2 s . com // get the payload in JSON format jsonPayload = payloadBuilder.toPayload().toString(); // build the REST URL... StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()); url.append("metrics/data"); // now send the REST request Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { log.errorFailedToStoreMetricData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } @Override public void onResponse(Response response) throws IOException { // HTTP status of 200 means success; anything else is an error if (response.code() != 200) { IOException e = new IOException("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); log.errorFailedToStoreMetricData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); throw e; } // looks like everything stored successfully diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints()); } }); } catch (Throwable t) { log.errorFailedToStoreMetricData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.hawkular.agent.monitor.storage.MetricsOnlyStorageAdapter.java
License:Apache License
@Override public void store(AvailDataPayloadBuilder payloadBuilder) { String jsonPayload = "?"; try {/*from ww w . ja v a 2 s .c o m*/ // get the payload in JSON format jsonPayload = payloadBuilder.toPayload().toString(); // build the REST URL... StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()); url.append("availability/data"); // now send the REST request Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { log.errorFailedToStoreAvailData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } @Override public void onResponse(Response response) throws IOException { // HTTP status of 200 means success; anything else is an error if (response.code() != 200) { IOException e = new IOException("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); log.errorFailedToStoreAvailData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); throw e; } // looks like everything stored successfully diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints()); } }); } catch (Throwable t) { log.errorFailedToStoreAvailData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }