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.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java
License:Apache License
private <L> void performResourceSync( InventoryStructure<org.hawkular.inventory.api.model.Resource.Blueprint> resourceStructure, String tenantIdToUse, int totalResourceCount) { if (resourceStructure.getRoot() != null) { try {/*w ww . j a v a 2s. co m*/ SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build(); SyncRequest<org.hawkular.inventory.api.model.Resource.Blueprint> sync; sync = new SyncRequest<>(syncConfig, resourceStructure); StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(), AsyncInventoryStorage.this.config.getInventoryContext()); url.append("sync"); url.append("/f;").append(this.feedId); url.append("/r;").append(Util.urlEncode(resourceStructure.getRoot().getId())); String jsonPayload = Util.toJson(sync); Map<String, String> headers = getTenantHeader(tenantIdToUse); log.tracef("Syncing [%d] resources to inventory: headers=[%s] body=[%s]", totalResourceCount, headers, jsonPayload); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload); Call call = this.httpClientBuilder.getHttpClient().newCall(request); final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time(); Response response = call.execute(); try { final long durationNanos = timer.stop(); log.tracef("Received sync response from inventory: code [%d]", response.code()); // HTTP status of 204 means success, anything else is an error if (response.code() != 204) { throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); } diagnostics.getInventoryRate().mark(totalResourceCount); if (log.isDebugEnabled()) { log.debugf("Took [%d]ms to sync [%d] resources to inventory", TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS), totalResourceCount); } } finally { response.body().close(); } } catch (InterruptedException ie) { log.errorFailedToStoreInventoryData(ie); Thread.currentThread().interrupt(); // preserve interrupt } catch (Exception e) { log.errorFailedToStoreInventoryData(e); diagnostics.getStorageErrorRate().mark(1); } } return; }
From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java
License:Apache License
private <L> void performResourceTypeSync( Offline<org.hawkular.inventory.api.model.ResourceType.Blueprint> resourceTypeStructure, String tenantIdToUse) {//from w w w . ja va2s . c o m if (resourceTypeStructure.getRoot() != null) { try { SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build(); SyncRequest<org.hawkular.inventory.api.model.ResourceType.Blueprint> sync; sync = new SyncRequest<>(syncConfig, resourceTypeStructure); StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(), AsyncInventoryStorage.this.config.getInventoryContext()); url.append("sync"); url.append("/f;").append(this.feedId); url.append("/rt;").append(Util.urlEncode(resourceTypeStructure.getRoot().getId())); String jsonPayload = Util.toJson(sync); Map<String, String> headers = getTenantHeader(tenantIdToUse); log.tracef("Syncing resource type to inventory: headers=[%s] body=[%s]", headers, jsonPayload); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload); Call call = this.httpClientBuilder.getHttpClient().newCall(request); final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time(); Response response = call.execute(); try { final long durationNanos = timer.stop(); log.tracef("Received sync response from inventory: code [%d]", response.code()); // HTTP status of 204 means success, anything else is an error if (response.code() != 204) { throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); } diagnostics.getInventoryRate().mark(1); if (log.isDebugEnabled()) { log.debugf("Took [%d]ms to sync resource type to inventory", TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS)); } } finally { response.body().close(); } } catch (InterruptedException ie) { log.errorFailedToStoreInventoryData(ie); Thread.currentThread().interrupt(); // preserve interrupt } catch (Exception e) { log.errorFailedToStoreInventoryData(e); diagnostics.getStorageErrorRate().mark(1); } } return; }
From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java
License:Apache License
private <L> void performMetricTypeSync( Offline<org.hawkular.inventory.api.model.MetricType.Blueprint> metricTypeStructure, String tenantIdToUse) {//ww w . ja v a2s . co m if (metricTypeStructure.getRoot() != null) { try { SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build(); SyncRequest<org.hawkular.inventory.api.model.MetricType.Blueprint> sync; sync = new SyncRequest<>(syncConfig, metricTypeStructure); StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(), AsyncInventoryStorage.this.config.getInventoryContext()); url.append("sync"); url.append("/f;").append(this.feedId); url.append("/mt;").append(Util.urlEncode(metricTypeStructure.getRoot().getId())); String jsonPayload = Util.toJson(sync); Map<String, String> headers = getTenantHeader(tenantIdToUse); log.tracef("Syncing metric type to inventory: headers=[%s] body=[%s]", headers, jsonPayload); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload); Call call = this.httpClientBuilder.getHttpClient().newCall(request); final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time(); Response response = call.execute(); try { final long durationNanos = timer.stop(); log.tracef("Received sync response from inventory: code [%d]", response.code()); // HTTP status of 204 means success, anything else is an error if (response.code() != 204) { throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); } diagnostics.getInventoryRate().mark(1); if (log.isDebugEnabled()) { log.debugf("Took [%d]ms to sync metric type to inventory", TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS)); } } finally { response.body().close(); } } catch (InterruptedException ie) { log.errorFailedToStoreInventoryData(ie); Thread.currentThread().interrupt(); // preserve interrupt } catch (Exception e) { log.errorFailedToStoreInventoryData(e); diagnostics.getStorageErrorRate().mark(1); } } return; }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(MetricDataPayloadBuilder payloadBuilder, long waitMillis) { String jsonPayload = "?"; try {//from ww w. j a va 2 s .co m // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // 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(), tenantIdHeader, jsonPayload); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreMetricData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // 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); } else { // looks like everything stored successfully diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints()); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } catch (Throwable t) { log.errorFailedToStoreMetricData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(AvailDataPayloadBuilder payloadBuilder, long waitMillis) { String jsonPayload = "?"; try {// ww w .j a va 2s. com // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // 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(), tenantIdHeader, jsonPayload); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); final String jsonPayloadFinal = jsonPayload; this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreAvailData(e, jsonPayloadFinal); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // 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); } else { // looks like everything stored successfully diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints()); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } catch (Throwable t) { log.errorFailedToStoreAvailData(t, jsonPayload); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java
License:Apache License
@Override public void store(MetricTagPayloadBuilder payloadBuilder, long waitMillis) { Map<String, String> jsonPayloads = null; try {//from ww w . ja va2s. com // Determine what tenant header to use. // If no tenant override is specified in the payload, use the agent's tenant ID. Map<String, String> tenantIdHeader; String metricTenantId = payloadBuilder.getTenantId(); if (metricTenantId == null) { tenantIdHeader = agentTenantIdHeader; } else { tenantIdHeader = getTenantHeader(metricTenantId); } // get the payload(s) jsonPayloads = payloadBuilder.toPayload(); // build the REST URL... String url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()).toString(); // The way the metrics REST API works is you can only add tags for one metric at a time // so loop through each metric ID and send one REST request for each one. for (Map.Entry<String, String> jsonPayload : jsonPayloads.entrySet()) { String relativePath = jsonPayload.getKey(); // this identifies the metric (e.g. "gauges/<id>") String tagsJson = jsonPayload.getValue(); String currentUrl = url + relativePath + "/tags"; // now send the REST request Request request = this.httpClientBuilder.buildJsonPutRequest(currentUrl, tenantIdHeader, tagsJson); final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1); this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { try { log.errorFailedToStoreMetricTags(e, tagsJson); diagnostics.getStorageErrorRate().mark(1); } finally { if (latch != null) { latch.countDown(); } } } @Override public void onResponse(Response response) throws IOException { try { // 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.errorFailedToStoreMetricTags(e, tagsJson); diagnostics.getStorageErrorRate().mark(1); } } finally { if (latch != null) { latch.countDown(); } response.body().close(); } } }); if (latch != null) { latch.await(waitMillis, TimeUnit.MILLISECONDS); } } } catch (Throwable t) { log.errorFailedToStoreMetricTags(t, (jsonPayloads == null) ? "?" : jsonPayloads.toString()); diagnostics.getStorageErrorRate().mark(1); } }
From source file:org.fuse.hawkular.agent.MonitorService.java
License:Apache License
private void waitForHawkularServer() throws Exception { OkHttpClient httpclient = this.httpClientBuilder.getHttpClient(); String statusUrl = Util.getContextUrlString(subsystemConfiguration.getStorageAdapter().getUrl(), subsystemConfiguration.getStorageAdapter().getMetricsContext()).append("status").toString(); Request request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null); while (true) { Response response = null; try {//from w ww .ja v a 2 s .c om 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); } if (this.subsystemConfiguration.getStorageAdapter().getType().toString().equals("HAWKULAR")) { statusUrl = Util .getContextUrlString(subsystemConfiguration.getStorageAdapter().getUrl(), subsystemConfiguration.getStorageAdapter().getInventoryContext()) .append("status").toString(); request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null); 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); } } }
From source file:org.fuse.hawkular.agent.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 *//*from w w w.j a va2 s .co 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(subsystemConfiguration.getStorageAdapter().getUrl(), subsystemConfiguration.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.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 {/*from w w w . j a v a 2 s. 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.inputs.transports.HttpPollTransport.java
License:Open Source License
@Override public void doLaunch(final MessageInput input) throws MisfireException { serverStatus.awaitRunning(new Runnable() { @Override//from ww w .j av a 2 s . co 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))); }