public void sendEvents() { if (!events.isEmpty()) { try { webResource.entity(events, MediaType.APPLICATION_JSON_TYPE).post(); } catch (Exception e) { log.error(e, "error occurred when sending metrics to opentsdb server."); } finally { events.clear(); } } } }
final ClientConfig config = new DefaultClientConfig(); final Client client = Client.create(config); final WebResource resource = client.resource(ENDPOINT_URL); final MimeMultipart request = new MimeMultipart(); request.addBodyPart(new MimeBodyPart(new FileInputStream(new File( fileName)))); final String response = resource .entity(request, "multipart/form-data") .accept("text/plain") .post(String.class);
@Override public void sendSystemAlert(String message) { if (StringUtils.isNotBlank(webhookUrl)) { Map<String, String> bodyMap = new HashMap<>(); bodyMap.put("text", message); bodyMap.put("channel", channel); String bodyJson = JsonUtils.convertToJsonString(bodyMap); WebResource resource = client.resource(webhookUrl); ClientResponse response = resource.entity(bodyJson).post(ClientResponse.class); int status = response.getStatus(); if (status != 200) { LOGGER.warn("Unable to send message to Slack, status={}, error={}, message={}", new Object[] { status, response.getEntity(String.class), message }); } } }
private void submit(String xmlFile) { File f = new File(xmlFile); if(!f.exists()) { System.err.printf("Job file %s does not exist!\n", xmlFile); System.exit(EXIT_FILE_NOT_FOUND); } Client client = new Client(); ClientResponse resp = client.resource(endpoint + "/job").entity(f, "application/xml").put(ClientResponse.class); LogMF.debug(l4j, "HTTP Response {0}:{1}", resp.getStatus(), resp.getStatusInfo().getReasonPhrase()); if(resp.getStatus() == 409) { System.err.println("Cannot submit job, another job is already running"); System.exit(EXIT_JOB_CONFLICT); } else if (resp.getStatus() > 399) { System.err.println("Error submitting job:\n" + resp.getEntity(String.class)); } String job = resp.getHeaders().getFirst("x-emc-job-id"); System.out.printf("Submitted Job %s\n", job); }
private void controlJob(int jobId, JobControl control) { Client client = new Client(); String uri = String.format("%s/job/%d/control", endpoint, jobId); ClientResponse response = client.resource(uri).entity(control, "application/xml").post(ClientResponse.class); if(response.getStatus() == 404) { System.out.printf("No job %d\n", jobId); System.exit(EXIT_NO_JOB); } else if(response.getStatus() == 200) { System.out.println("Command completed successfully"); System.exit(EXIT_SUCCESS); } else { System.err.printf("Error controlling job %d: HTTP %d: %s\n", jobId, response.getStatus(), response.getStatusInfo().getReasonPhrase()); String s = response.getEntity(String.class); if(s != null) { System.err.println(s); } System.exit(EXIT_UNKNOWN_ERROR); } }
/** * Update the cart items * * @param clientUser The authenticated client user * * @return A matching {@link org.multibit.mbm.client.interfaces.rest.api.item.ItemDto} */ public CartDto updateCartItems(UserDto clientUser, List<PublicCartItemDto> cartItems) { // Sanity check Preconditions.checkNotNull(clientUser); Preconditions.checkNotNull(clientUser.getApiKey()); Preconditions.checkNotNull(clientUser.getSecretKey()); // TODO Replace "magic string" with auto-discover based on link rel String path = String.format("/cart"); UpdateCartDto updateCartRequest = new UpdateCartDto(); updateCartRequest.setCartItems(cartItems); String hal = HalHmacResourceFactory.INSTANCE .newUserResource(locale, path, clientUser) .entity(updateCartRequest, MediaType.APPLICATION_JSON_TYPE) .put(String.class); // Read the HAL ReadableRepresentation rr = unmarshalHal(hal); Map<String, Object> properties = rr.getProperties(); return buildClientCart(rr, properties); }
/** * Update the cart items * * @param clientUser The authenticated client user * * @return A matching {@link org.multibit.mbm.client.interfaces.rest.api.item.ItemDto} */ public CartDto updateCartItems(UserDto clientUser, List<PublicCartItemDto> cartItems) { // Sanity check Preconditions.checkNotNull(clientUser); Preconditions.checkNotNull(clientUser.getApiKey()); Preconditions.checkNotNull(clientUser.getSecretKey()); // TODO Replace "magic string" with auto-discover based on link rel String path = String.format("/cart"); UpdateCartDto updateCartRequest = new UpdateCartDto(); updateCartRequest.setCartItems(cartItems); String hal = HalHmacResourceFactory.INSTANCE .newUserResource(locale, path, clientUser) .entity(updateCartRequest, MediaType.APPLICATION_JSON_TYPE) .put(String.class); // Read the HAL ReadableRepresentation rr = unmarshalHal(hal); Map<String, Object> properties = rr.getProperties(); return buildClientCart(rr, properties); }
.entity(entity, HalMediaType.APPLICATION_JSON_TYPE) .post(String.class);
.entity(entity, HalMediaType.APPLICATION_JSON_TYPE) .post(String.class);
.entity(entity, HalMediaType.APPLICATION_JSON_TYPE) .post(String.class);
builder = webResource.entity(formParam, mediaType); builder = builder.accept(mediaType); } else {
public void updateGeometry(ResourceId formId, ResourceId recordId, ResourceId fieldId, Geometry value) { ClientResponse response = client.resource(root) .path("form") .path(formId.asString()) .path("record") .path(recordId.asString()) .path("field") .path(fieldId.asString()) .path("geometry") .entity(toWkbBinary(value)) .post(ClientResponse.class); if(response.getStatus() != 200) { throw new RuntimeException("Failed with status code: " + response.getStatus() + ", message: " + firstLine(response.getEntity(String.class))); } }
/** * {@inheritDoc} */ @Override public <T> T put(Object o, Class<T> responseEntity) { AhcHttpClient asyncClient = AhcHttpClient.create(createAhcConfig()); o = quoteString(o); try { WebResource r = buildRequest(asyncClient); r.entity(o); ClientResponse response = headers(r, TYPE.PUT).put(ClientResponse.class, o); checkStatus(response); return checkVoid(response, responseEntity); } catch (UniformInterfaceException u) { headers.put(negotiateHandler.challengedHeaderName(), negotiate(u)); return put(o, responseEntity); } finally { asyncClient.destroy(); } }
private ClientResponse submitAndVerifyReservation(String path, String media, String reservationJson) throws Exception { JSONJAXBContext jc = new JSONJAXBContext(JSONConfiguration.mapped() .build(), ReservationSubmissionRequestInfo.class); JSONUnmarshaller unmarshaller = jc.createJSONUnmarshaller(); ReservationSubmissionRequestInfo rsci = unmarshaller.unmarshalFromJSON(new StringReader(reservationJson), ReservationSubmissionRequestInfo.class); Thread.sleep(1000); ClientResponse response = constructWebResource(path).entity(rsci, MediaType.APPLICATION_JSON) .accept(media).post(ClientResponse.class); if (!this.isAuthenticationEnabled()) { assertResponseStatusCode(Status.UNAUTHORIZED, response.getStatusInfo()); } return response; }
private void insertUsers(List<String> users) { Client client = Client.create(); WebResource userResources = client.resource(server.getRootUrl()).path("resources").path("users"); // LOGGER.info("Creating new account via " + userResources); for(String user : users) { Form form = new Form(); form.putSingle("email", user); form.putSingle("name", nameForEmail(user)); form.putSingle("password", DEV_PASSWORD); form.putSingle("locale", locale); ClientResponse response = userResources.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class); if(response.getStatus() == Response.Status.CREATED.getStatusCode()) { // LOGGER.info("User " + user + " created " + response.getStatus()); } else { throw new RuntimeException("Could not create user " + user + ": " + response.getClientResponseStatus() + "\n" + response.getEntity(String.class)); } } }
@Test public void test() throws Exception { UploadCredentials credentials = new GcsUploadCredentialBuilder(new TestingIdentityService(PRIVATE_KEY_FILE_PATH), "file.png"). setCreatorId(CuidAdapter.userId(1)). setOwnerId(ResourceId.generateId()). setBucket("ai-dev-field-blob-test"). setKey(BlobId.generate().asString()). setMaxContentLengthInMegabytes(10). expireAfter(Duration.standardMinutes(5)). build(); FormDataMultiPart form = new FormDataMultiPart(); for (Map.Entry<String, String> entry : credentials.getFormFields().entrySet()) { form.field(entry.getKey(), entry.getValue()); } form.field("file", Resources.asByteSource(Resources.getResource(getClass(), "goabout.png")).read(), MediaType.valueOf(PNG.toString())); Client.create() .resource(credentials.getUrl()) .entity(form, MediaType.MULTIPART_FORM_DATA_TYPE) .post(); }
private void updateReservationTestHelper(String path, ReservationId reservationId, String media) throws Exception { String reservationJson = loadJsonFile("update-reservation.json"); JSONJAXBContext jc = new JSONJAXBContext(JSONConfiguration.mapped() .build(), ReservationUpdateRequestInfo.class); JSONUnmarshaller unmarshaller = jc.createJSONUnmarshaller(); ReservationUpdateRequestInfo rsci = unmarshaller.unmarshalFromJSON(new StringReader(reservationJson), ReservationUpdateRequestInfo.class); if (this.isAuthenticationEnabled()) { // only works when previous submit worked if(rsci.getReservationId() == null) { throw new IOException("Incorrectly parsed the reservationId"); } rsci.setReservationId(reservationId.toString()); } Thread.sleep(1000); ClientResponse response = constructWebResource(path).entity(rsci, MediaType.APPLICATION_JSON) .accept(media).post(ClientResponse.class); if (!this.isAuthenticationEnabled()) { assertResponseStatusCode(Status.UNAUTHORIZED, response.getStatusInfo()); return; } System.out.println("RESPONSE:" + response); assertEquals(MediaType.APPLICATION_JSON_TYPE + "; " + JettyUtils.UTF_8, response.getType().toString()); assertResponseStatusCode(Status.OK, response.getStatusInfo()); }
constructWebResource(path).entity(rsci, MediaType.APPLICATION_JSON) .accept(media).post(ClientResponse.class);
.constructWebResource("apps", app.getApplicationId().toString(), "state") .entity(entity, contentType).accept(mediaType) .put(ClientResponse.class);
.constructWebResource("apps", app.getApplicationId().toString(), "state") .entity(entity, contentType).accept(mediaType) .put(ClientResponse.class);