List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:org.hawkular.agent.monitor.dynamicprotocol.prometheus.HawkularPrometheusScraper.java
License:Apache License
@Override protected OpenConnectionDetails openConnection(URL endpointUrl) throws IOException { Configuration.Builder bldr = new Configuration.Builder().useSsl(endpointUrl.getProtocol().equals("https")) .sslContext(sslContext).username(endpointConfig.getConnectionData().getUsername()) .password(endpointConfig.getConnectionData().getPassword()); BaseHttpClientGenerator httpClientGen = new BaseHttpClientGenerator(bldr.build()); OkHttpClient httpClient = httpClientGen.getHttpClient(); Request request = buildGetRequest(endpointUrl, httpClientGen); Call call = httpClient.newCall(request); Response response = call.execute(); ResponseBody responseBody = response.body(); InputStream inputStream = responseBody.byteStream(); MediaType contentType = responseBody.contentType(); return new OpenConnectionDetails(inputStream, (contentType != null) ? contentType.toString() : null); }
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 {// w w w . j av a 2s.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); 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 *//* w ww . ja v a 2s . 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.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 w w w . j a v a2 s . c o m Assert.fail("Could not get [" + statusUrl + "]: " + response.code() + " " + response.message()); } }
From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public <T> T post(String url, Class<T> returnType, Object requestObject) throws Exception { final OkHttpClient httpClient = getHttpClient(); Request.Builder builder = new Request.Builder(); builder.url(url);// w ww.j av a 2s . co m if (requestObject != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(requestObject); oos.flush(); } catch (Exception e) { throw new RuntimeException("Error sending request Object, " + requestObject, e); } RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray()); builder.post(body); } Request request = builder.build(); Response response = httpClient.newCall(request).execute(); int responseCode = response.code(); if (responseCode == HttpURLConnection.HTTP_OK) { Object o; try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) { o = ois.readObject(); } if (returnType.isInstance(o) == false) { throw new IllegalStateException( "Error reading results, expected a " + returnType.getName() + " but got " + o); } return returnType.cast(o); } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) { throw new IllegalStateException( "Error launching test at " + url + ". Got " + responseCode + " (" + response.message() + ")"); } return null; // TODO }
From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public synchronized InputStream post(Map<String, String> labels, int index, int port, String path) throws Exception { String url = url(labels, index, port, path, null); OkHttpClient httpClient = getHttpClient(); Request.Builder builder = new Request.Builder(); builder.url(url);/*from w w w . j a va2 s . co m*/ Request request = builder.build(); Response response = httpClient.newCall(request).execute(); return response.body().byteStream(); }
From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public int status(String url) { try {/*from w w w. j av a2s . c o m*/ OkHttpClient httpClient = getHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); return response.code(); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java
License:Apache License
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = globalClient.clone(); requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri())); Response response = requestScopedClient.newCall(nativeRequest).execute(); HttpResponse.Builder<?> builder = HttpResponse.builder(); builder.statusCode(response.code()); builder.message(response.message()); Builder<String, String> headerBuilder = ImmutableMultimap.builder(); Headers responseHeaders = response.headers(); for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); }//www.j a v a 2s . c o m ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }
From source file:org.jenkinsci.tools.bce.JenkinsBCEMojo.java
License:Open Source License
private ResolvedArtifact getUpdateCenterBaseline() throws MojoFailureException { final String url = getBaselinePayload(UPDATE_CENTER); if (url == null || url.isEmpty()) { return null; }/* w ww. j a v a 2 s . c om*/ final JsonElement updates; try { // TODO: look for internal Maven URL downloading methods (using proxies, etc.) final OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); String response = client.newCall(request).execute().body().string(); // TODO: review JSONP parsing response = response.substring(response.indexOf('{')); response = response.substring(0, response.lastIndexOf(')')); updates = new JsonParser().parse(new JsonReader(new StringReader(response))); } catch (Exception e) { throw failure(e, "Unable to get plugin information from update center [%s]", url); } // TODO: error reporting, new plugins, etc. final String coordinates; try { coordinates = updates.getAsJsonObject().get("plugins").getAsJsonObject() .get(mavenProject.getArtifactId()).getAsJsonObject().get("gav").getAsString(); } catch (RuntimeException e) { throw failure(e, "Unable to get plugin coordinates from update center [%s] info", url); } return new ResolvedArtifact(parseArtifact(coordinates)); }
From source file:org.mythtv.services.api.ServerVersionQuery.java
License:Apache License
private static ApiVersion getMythVersion(String baseUri, OkHttpClient client) throws IOException { StringBuilder urlBuilder = new StringBuilder(baseUri); if (!baseUri.endsWith("/")) urlBuilder.append("/"); urlBuilder.append("Myth/GetHostName"); Request request = new Request.Builder().url(urlBuilder.toString()) .addHeader("User-Agent", "MythTv Service API").addHeader("Connection", "Close").build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String serverHeader = response.header(MYTHTV_SERVER_HEADER); if (!Strings.isNullOrEmpty(serverHeader)) { // we have our header get the version. int idx = serverHeader.indexOf(MYTHTV_SERVER_MYTHVERSION); if (idx >= 0) { idx += MYTHTV_SERVER_MYTHVERSION.length(); String version = serverHeader.substring(idx); if (version.contains("0.27")) return ApiVersion.v027; if (version.contains("0.28")) return ApiVersion.v028; }//w ww. ja v a2 s. c om } } return ApiVersion.NotSupported; }