List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:io.kodokojo.bdd.stage.ApplicationWhen.java
License:Open Source License
private SELF create_user(String email, boolean success) { if (isBlank(email)) { throw new IllegalArgumentException("email must be defined."); }// w ww . ja v a2 s . co m if (success && StringUtils.isBlank(newUserId)) { retrive_a_new_id(); } OkHttpClient httpClient = new OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/json"), ("{\"email\": \"" + email + "\"}").getBytes()); String baseUrl = getBaseUrl(); Request.Builder builder = new Request.Builder().post(body) .url(baseUrl + "/api/v1/user" + (newUserId != null ? "/" + newUserId : "")); if (isNotBlank(currentUserLogin)) { UserInfo currentUser = currentUsers.get(currentUserLogin); if (currentUser != null) { builder = HttpUserSupport.addBasicAuthentification(currentUser, builder); } } Request request = builder.build(); Response response = null; try { response = httpClient.newCall(request).execute(); if (success) { assertThat(response.code()).isEqualTo(201); JsonParser parser = new JsonParser(); String bodyResponse = response.body().string(); JsonObject json = (JsonObject) parser.parse(bodyResponse); String currentUsername = json.getAsJsonPrimitive("username").getAsString(); String currentUserPassword = json.getAsJsonPrimitive("password").getAsString(); String currentUserEmail = json.getAsJsonPrimitive("email").getAsString(); String currentUserIdentifier = json.getAsJsonPrimitive("identifier").getAsString(); String currentUserEntityIdentifier = json.getAsJsonPrimitive("entityIdentifier").getAsString(); currentUsers.put(currentUsername, new UserInfo(currentUsername, currentUserIdentifier, currentUserEntityIdentifier, currentUserPassword, currentUserEmail)); if (isBlank(currentUserLogin)) { currentUserLogin = currentUsername; } Attachment privateKey = Attachment.plainText(bodyResponse).withTitle(currentUsername + " response"); currentStep.addAttachment(privateKey); } else { assertThat(response.code()).isNotEqualTo(201); } response.body().close(); } catch (IOException e) { if (success) { fail(e.getMessage(), e); } } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return self(); }
From source file:io.kodokojo.bdd.stage.HttpUserSupport.java
License:Open Source License
public UserInfo createUser(UserInfo currentUser, String email) { RequestBody emptyBody = RequestBody.create(null, new byte[0]); Request.Builder builder = new Request.Builder().post(emptyBody).url(getApiBaseUrl() + "/user"); if (currentUser != null) { builder = addBasicAuthentification(currentUser, builder); }// w ww. j av a2 s. co m Request request = builder.build(); Response response = null; String identifier = null; try { response = httpClient.newCall(request).execute(); identifier = response.body().string(); assertThat(identifier).isNotEmpty(); } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } RequestBody body = RequestBody.create(MediaType.parse("application/json"), ("{\"email\": \"" + email + "\"}").getBytes()); builder = new Request.Builder().post(body).url(getApiBaseUrl() + "/user/" + identifier); if (currentUser != null) { builder = addBasicAuthentification(currentUser, builder); } request = builder.build(); response = null; try { response = httpClient.newCall(request).execute(); JsonParser parser = new JsonParser(); String bodyResponse = response.body().string(); JsonObject json = (JsonObject) parser.parse(bodyResponse); String currentUsername = json.getAsJsonPrimitive("username").getAsString(); String currentUserPassword = json.getAsJsonPrimitive("password").getAsString(); String currentUserEmail = json.getAsJsonPrimitive("email").getAsString(); String currentUserIdentifier = json.getAsJsonPrimitive("identifier").getAsString(); String currentUserEntityIdentifier = json.getAsJsonPrimitive("entityIdentifier").getAsString(); UserInfo res = new UserInfo(currentUsername, currentUserIdentifier, currentUserEntityIdentifier, currentUserPassword, currentUserEmail); return res; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return null; }
From source file:io.kodokojo.bdd.stage.HttpUserSupport.java
License:Open Source License
public String createProjectConfiguration(String projectName, StackConfigDto stackConfigDto, UserInfo currentUser) {// w ww . j a va 2s. c o m if (isBlank(projectName)) { throw new IllegalArgumentException("projectName must be defined."); } String json = generateProjectConfigurationDto(projectName, currentUser, stackConfigDto); RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.getBytes()); Request.Builder builder = new Request.Builder().url(getApiBaseUrl() + "/projectconfig").post(body); Request request = addBasicAuthentification(currentUser, builder).build(); Response response = null; try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(201); String payload = response.body().string(); return payload; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return null; }
From source file:io.kodokojo.bdd.stage.HttpUserSupport.java
License:Open Source License
private static Request.Builder createChangeUserOnProjectConfiguration(String apiBaseurl, String projectConfigurationId, String json, UserChangeProjectConfig userChangeProjectConfig) { RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.getBytes()); Request.Builder builder = new Request.Builder() .url(apiBaseurl + "/projectconfig/" + projectConfigurationId + "/user"); if (userChangeProjectConfig == UserChangeProjectConfig.ADD) { builder = builder.put(body);/*from w w w.jav a2 s .c om*/ } else { builder = builder.delete(body); } return builder; }
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) {/* ww w.j ava 2 s . c om*/ 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.service.marathon.MarathonConfigurationStore.java
License:Open Source License
@Override public boolean storeBootstrapStackData(BootstrapStackData bootstrapStackData) { if (bootstrapStackData == null) { throw new IllegalArgumentException("bootstrapStackData must be defined."); }//w ww .j av a 2 s. c o 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."); }/*from w w w .j a v a2s . c o 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; }
From source file:io.macgyver.neorx.rest.NeoRxClient.java
License:Apache License
protected ObjectNode execRawCypher(String cypher, ObjectNode params) { try {/* ww w . j av a 2 s .co m*/ ObjectNode payload = formatPayload(cypher, params); String payloadString = payload.toString(); OkHttpClient c = getClient(); checkNotNull(c); String requestId = newRequestId(); if (logger.isDebugEnabled()) { logger.debug(String.format("request[%s]: %s", requestId, payloadString)); } Builder builder = injectCredentials(new Request.Builder()) .addHeader("X-Stream", Boolean.toString(streamResponse)).addHeader("Accept", "application/json") .url(getUrl() + "/db/data/transaction/commit") .post(RequestBody.create(MediaType.parse("application/json"), payloadString)); if (!GuavaStrings.isNullOrEmpty(username) && !GuavaStrings.isNullOrEmpty(password)) { builder = builder.addHeader("Authorization", Credentials.basic(username, password)); } com.squareup.okhttp.Response r = c.newCall(builder.build()).execute(); ObjectNode jsonResponse = (ObjectNode) mapper.readTree(r.body().charStream()); if (logger.isDebugEnabled()) { logger.debug(String.format("response[%s]: %s", requestId, jsonResponse.toString())); } ObjectNode n = jsonResponse; JsonNode error = n.path("errors").path(0); if (error instanceof ObjectNode) { throw new NeoRxException(((ObjectNode) error)); } return n; } catch (IOException e) { throw new NeoRxException(e); } }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
public Response execute(RequestBuilder b) { try {/*from ww w .j a v a 2s .c o m*/ String method = b.getMethod(); Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed"); String url = null; Response resp; String format = b.getParams().getOrDefault("format", "xml"); b = b.param("format", format); if (!b.hasBody()) { url = formatUrl(b.getParams(), format); FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken()); for (Map.Entry<String, String> entry : b.getParams().entrySet()) { if (!entry.getValue().equals("format")) { fb = fb.add(entry.getKey(), entry.getValue()); } } resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute(); } else if (b.getXmlBody().isPresent()) { b = b.param("format", "xml"); url = formatUrl(b.getParams(), "xml"); String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get()); final MediaType XML = MediaType.parse("text/xml"); resp = getClient().newCall(new Request.Builder().url(url) .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build()) .execute(); } else if (b.getJsonBody().isPresent()) { b = b.param("format", "json"); url = formatUrl(b.getParams(), "json"); String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get()); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); resp = getClient().newCall(new Request.Builder().url(url).post( RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build()) .execute(); } else { throw new UnsupportedOperationException("body type not supported"); } // the A10 API rather stupidly uses 200 responses even when there is // an error if (!resp.isSuccessful()) { logger.warn("response code={}", resp.code()); } return resp; } catch (IOException e) { throw new ElbException(e); } }
From source file:io.macgyver.plugin.pagerduty.PagerDutyClientImpl.java
License:Apache License
public ObjectNode postEvent(ObjectNode input) { try {/* w w w . j a va2s. c o m*/ Request r = new Request.Builder().url(eventsEndpointUrl + "/create_event.json") .post(RequestBody.create(MediaType.parse("application/json"), input.toString())) .addHeader("Accept", org.springframework.http.MediaType.APPLICATION_JSON_VALUE).build(); Response response = getEventClient().newCall(r).execute(); ObjectNode rv = (ObjectNode) mapper.readTree(response.body().string()); throwExceptionIfNecessary(rv); return rv; } catch (IOException e) { throw new MacGyverException(e); } }