List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:io.kodokojo.bdd.stage.brickauthenticator.NexusUserAuthenticator.java
License:Open Source License
@Override public boolean authenticate(OkHttpClient httpClient, String url, UserInfo userInfo) { Request.Builder builder = new Request.Builder().url(url + "/service/local/users"); builder = HttpUserSupport.addBasicAuthentification(userInfo, builder); Request request = builder.build(); Response response = null;/*from w w w. j av a 2 s .c o m*/ try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isBetween(200, 299); return true; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return false; }
From source file:io.kodokojo.bdd.stage.BrickConfigurerGiven.java
License:Open Source License
private boolean waitBrickStarted(String brickUrl, int timeout) { boolean started = false; long now = System.currentTimeMillis(); long end = now + (timeout * 1000); OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().get().url(brickUrl).build(); while (!started && (end - System.currentTimeMillis()) > 0) { Response response = null; try {/*from w w w . j a v a 2 s . c o m*/ response = httpClient.newCall(request).execute(); int httpStatusCode = response.code(); started = httpStatusCode >= 200 && httpStatusCode < 300; } catch (IOException e) { // Silently ignore, service maybe not available started = false; } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } if (!started) { try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } try { Thread.sleep(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return started; }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void killApp(String appId) { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().delete().url(marathonUrl + "/v2/apps/" + appId).build(); try {/* w ww . jav a 2 s.co m*/ Response response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); } catch (IOException e) { LOGGER.error("Unable to kill app {}.", appId, e); } }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void killAllAppInMarathon(String marathonUrl) { OkHttpClient httpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder().url(marathonUrl + "/v2/apps").get(); Response response = null;/* w w w. ja va2s . co m*/ Set<String> appIds = new HashSet<>(); try { response = httpClient.newCall(builder.build()).execute(); String body = response.body().string(); JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(body); JsonArray apps = json.getAsJsonArray("apps"); for (JsonElement appEl : apps) { JsonObject app = (JsonObject) appEl; appIds.add(app.getAsJsonPrimitive("id").getAsString()); } } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } appIds.stream().forEach(id -> { Request.Builder rmBuilder = new Request.Builder().url(marathonUrl + "/v2/apps/" + id).delete(); Response responseRm = null; try { LOGGER.debug("Delete Marathon application id {}.", id); responseRm = httpClient.newCall(rmBuilder.build()).execute(); } catch (IOException e) { fail(e.getMessage()); } finally { if (responseRm != null) { IOUtils.closeQuietly(responseRm.body()); } } }); }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationWhen.java
License:Open Source License
public SELF i_start_the_project() { OkHttpClient httpClient = new OkHttpClient(); String url = "http://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/project/" + projectConfiguration.getIdentifier(); RequestBody body = RequestBody.create(null, new byte[0]); Request.Builder builder = new Request.Builder().url(url).post(body); builder = HttpUserSupport.addBasicAuthentification(currentUser, builder); Response response = null;//from w w w. j a v a 2 s. c o m try { response = httpClient.newCall(builder.build()).execute(); assertThat(response.code()).isEqualTo(201); LOGGER.trace("Starting project"); Map<String, Boolean> brickRunning = new HashMap<>(); projectConfiguration.getDefaultBrickConfigurations().forEachRemaining(b -> { brickRunning.put(b.getName(), Boolean.FALSE); }); JsonParser parser = new JsonParser(); boolean allBrickStarted = true; long now = System.currentTimeMillis(); long end = now + 180000; do { Iterator<String> messageReceive = webSocketEventsListener.getMessages().iterator(); while (messageReceive.hasNext()) { String message = messageReceive.next(); JsonObject root = (JsonObject) parser.parse(message); if ("updateState".equals(root.getAsJsonPrimitive("action").getAsString())) { JsonObject data = root.getAsJsonObject("data"); String brickName = data.getAsJsonPrimitive("brickName").getAsString(); String brickState = data.getAsJsonPrimitive("state").getAsString(); if ("RUNNING".equals(brickState)) { brickRunning.put(brickName, Boolean.TRUE); } } } Iterator<Boolean> iterator = brickRunning.values().iterator(); allBrickStarted = true; while (allBrickStarted && iterator.hasNext()) { allBrickStarted = iterator.next(); } if (!allBrickStarted) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } now = System.currentTimeMillis(); } while (!allBrickStarted && now < end); assertThat(allBrickStarted).isTrue(); } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return self(); }
From source file:io.kodokojo.brick.jenkins.JenkinsConfigurer.java
License:Open Source License
private BrickConfigurerData executeGroovyScript(BrickConfigurerData brickConfigurerData, VelocityContext context, String templatePath) { String url = brickConfigurerData.getEntrypoint() + SCRIPT_URL_SUFFIX; OkHttpClient httpClient = new OkHttpClient(); Response response = null;/* w w w .j a v a 2 s.co m*/ try { VelocityEngine ve = new VelocityEngine(); ve.init(VE_PROPERTIES); Template template = ve.getTemplate(templatePath); StringWriter sw = new StringWriter(); template.merge(context, sw); String script = sw.toString(); RequestBody body = new FormEncodingBuilder().add(SCRIPT_KEY, script).build(); Request.Builder builder = new Request.Builder().url(url).post(body); User admin = brickConfigurerData.getDefaultAdmin(); String crendential = String.format("%s:%s", admin.getUsername(), admin.getPassword()); builder.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(crendential.getBytes())); Request request = builder.build(); response = httpClient.newCall(request).execute(); if (response.code() >= 200 && response.code() < 300) { return brickConfigurerData; } throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint() + ". Jenkins return " + response.code());//Create a dedicate Exception instead. } catch (IOException e) { throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint(), e); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } }
From source file:io.kodokojo.brick.nexus.NexusConfigurer.java
License:Open Source License
private boolean executeRequest(OkHttpClient httpClient, String url, String xmlBody, String login, String password) {/*from w ww. j a v a 2s . c o m*/ RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml"), xmlBody); Request request = new Request.Builder().url(url) .addHeader("Authorization", encodeBasicAuth(login, password)).post(requestBody).build(); Response response = null; try { response = httpClient.newCall(request).execute(); return response.code() >= 200 && response.code() < 300; } catch (IOException e) { LOGGER.error("Unable to complete request on Nexus url {}", url, e); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return false; }
From source file:io.kodokojo.commons.utils.docker.DockerSupport.java
License:Open Source License
private boolean tryRequest(HttpUrl url, OkHttpClient httpClient, ServiceIsUp serviceIsUp) { Response response = null;//from w w w .j ava2s. co m try { Request request = new Request.Builder().url(url).get().build(); Call call = httpClient.newCall(request); response = call.execute(); boolean isSuccesseful = serviceIsUp.accept(response); response.body().close(); return isSuccesseful; } catch (IOException e) { return false; } finally { if (response != null) { try { response.body().close(); } catch (IOException e) { LOGGER.warn("Unable to close response."); } } } }
From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java
License:Open Source License
@Override public boolean storeBootstrapStackData(BootstrapStackData bootstrapStackData) { if (bootstrapStackData == null) { throw new IllegalArgumentException("bootstrapStackData must be defined."); }/*from w ww. ja v a2s. co m*/ String url = marathonUrl + "/v2/artifacts/config/" + bootstrapStackData.getProjectName().toLowerCase() + ".json"; OkHttpClient httpClient = new OkHttpClient(); Gson gson = new GsonBuilder().create(); String json = gson.toJson(bootstrapStackData); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", bootstrapStackData.getProjectName().toLowerCase() + ".json", RequestBody.create(MediaType.parse("application/json"), json.getBytes())) .build(); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = null; try { response = httpClient.newCall(request).execute(); return response.code() == 200; } catch (IOException e) { LOGGER.error("Unable to store configuration for project {}", bootstrapStackData.getProjectName(), e); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return false; }
From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java
License:Open Source License
@Override public boolean storeSSLKeys(String project, String entityName, SSLKeyPair sslKeyPair) { if (isBlank(project)) { throw new IllegalArgumentException("project must be defined."); }//ww w . j a v a 2s . co m if (isBlank(entityName)) { throw new IllegalArgumentException("entityName must be defined."); } if (sslKeyPair == null) { throw new IllegalArgumentException("sslKeyPair must be defined."); } Response response = null; try { Writer writer = new StringWriter(); SSLUtils.writeSSLKeyPairPem(sslKeyPair, writer); byte[] certificat = writer.toString().getBytes(); String url = marathonUrl + "/v2/artifacts/ssl/" + project.toLowerCase() + "/" + entityName.toLowerCase() + "/" + project.toLowerCase() + "-" + entityName.toLowerCase() + "-server.pem"; OkHttpClient httpClient = new OkHttpClient(); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", project + "-" + entityName + "-server.pem", RequestBody.create(MediaType.parse("application/text"), certificat)) .build(); Request request = new Request.Builder().url(url).post(requestBody).build(); response = httpClient.newCall(request).execute(); int code = response.code(); if (code > 200 && code < 300) { LOGGER.info("Push SSL certificate on marathon url '{}' [content-size={}]", url, certificat.length); } else { LOGGER.error("Fail to push SSL certificate on marathon url '{}' status code {}. Body response:\n{}", url, code, response.body().string()); } return code > 200 && code < 300; } catch (IOException e) { LOGGER.error("Unable to store ssl key for project {} and brick {}", project, entityName, e); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return false; }