List of usage examples for org.apache.http.client.methods HttpPatch HttpPatch
public HttpPatch(final String uri)
From source file:com.mxhero.plugin.cloudstorage.onedrive.api.Items.java
/** * Patch move./*from w w w.jav a 2s . c om*/ * * @param path the path * @param parentReference the parent reference * @return the item */ private Item patchMove(final String path, final ItemReference parentReference) { final Command<Item> command = this.commandFactory.create(); return command.excecute(new CommandHandler<Item>() { @Override public Item response(HttpResponse response) { try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return OneDrive.JACKSON.readValue(EntityUtils.toString(response.getEntity()), Item.class); } if (response.getStatusLine().getStatusCode() > 399) { throw new ApiException(response); } throw new IllegalArgumentException( "error reading response body with code " + response.getStatusLine().getStatusCode()); } catch (Exception e) { throw new IllegalArgumentException("error reading response", e); } } @Override public HttpUriRequest request() { HttpPatch httpPatch = new HttpPatch(command.baseUrl() + path); httpPatch.setHeader("Content-type", "application/json"); StringEntity entity; try { Map<String, Object> body = new HashMap<>(); body.put("parentReference", parentReference); entity = new StringEntity(OneDrive.JACKSON.writeValueAsString(body), "UTF-8"); } catch (Exception e) { throw new IllegalArgumentException("error sending path for " + path, e); } httpPatch.setEntity(entity); return httpPatch; } }); }
From source file:com.ibm.iotf.client.api.APIClient.java
private HttpResponse casePatchFromConnect(List<NameValuePair> queryParameters, String url, String method, StringEntity input, String encodedString) throws URISyntaxException, IOException { URIBuilder putBuilder = new URIBuilder(url); if (queryParameters != null) { putBuilder.setParameters(queryParameters); }// w ww .j a v a 2s .c o m HttpPatch patch = new HttpPatch(putBuilder.build()); patch.setEntity(input); patch.addHeader("Content-Type", "application/json"); patch.addHeader("Accept", "application/json"); patch.addHeader("Authorization", "Basic " + encodedString); try { HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build(); return client.execute(patch); } catch (IOException e) { LoggerUtility.warn(CLASS_NAME, method, e.getMessage()); throw e; } }
From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java
/** * Creates and returns a new HttpClient HTTP method based on the specified parameters. * @param submitMethod the submit method being used * @param uri the uri being used/*from w w w. j a v a 2 s . co m*/ * @return a new HttpClient HTTP method based on the specified parameters */ private static HttpRequestBase buildHttpMethod(final HttpMethod submitMethod, final URI uri) { final HttpRequestBase method; switch (submitMethod) { case GET: method = new HttpGet(uri); break; case POST: method = new HttpPost(uri); break; case PUT: method = new HttpPut(uri); break; case DELETE: method = new HttpDelete(uri); break; case OPTIONS: method = new HttpOptions(uri); break; case HEAD: method = new HttpHead(uri); break; case TRACE: method = new HttpTrace(uri); break; case PATCH: method = new HttpPatch(uri); break; default: throw new IllegalStateException("Submit method not yet supported: " + submitMethod); } return method; }
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
private HttpUriRequest performRandomRequest(String method) throws Exception { String uriAsString = "/" + randomStatusCode(getRandom()); URIBuilder uriBuilder = new URIBuilder(uriAsString); final Map<String, String> params = new HashMap<>(); boolean hasParams = randomBoolean(); if (hasParams) { int numParams = randomIntBetween(1, 3); for (int i = 0; i < numParams; i++) { String paramKey = "param-" + i; String paramValue = randomAsciiOfLengthBetween(3, 10); params.put(paramKey, paramValue); uriBuilder.addParameter(paramKey, paramValue); }/*ww w . j a va 2 s .c om*/ } if (randomBoolean()) { //randomly add some ignore parameter, which doesn't get sent as part of the request String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes())); if (randomBoolean()) { ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes())); } params.put("ignore", ignore); } URI uri = uriBuilder.build(); HttpUriRequest request; switch (method) { case "DELETE": request = new HttpDeleteWithEntity(uri); break; case "GET": request = new HttpGetWithEntity(uri); break; case "HEAD": request = new HttpHead(uri); break; case "OPTIONS": request = new HttpOptions(uri); break; case "PATCH": request = new HttpPatch(uri); break; case "POST": request = new HttpPost(uri); break; case "PUT": request = new HttpPut(uri); break; case "TRACE": request = new HttpTrace(uri); break; default: throw new UnsupportedOperationException("method not supported: " + method); } HttpEntity entity = null; boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean(); if (hasBody) { entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON); ((HttpEntityEnclosingRequest) request).setEntity(entity); } Header[] headers = new Header[0]; final Set<String> uniqueNames = new HashSet<>(); if (randomBoolean()) { headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); for (Header header : headers) { request.addHeader(header); uniqueNames.add(header.getName()); } } for (Header defaultHeader : defaultHeaders) { // request level headers override default headers if (uniqueNames.contains(defaultHeader.getName()) == false) { request.addHeader(defaultHeader); } } try { if (hasParams == false && hasBody == false && randomBoolean()) { restClient.performRequest(method, uriAsString, headers); } else if (hasBody == false && randomBoolean()) { restClient.performRequest(method, uriAsString, params, headers); } else { restClient.performRequest(method, uriAsString, params, entity, headers); } } catch (ResponseException e) { //all good } return request; }
From source file:com.semagia.cassa.client.GraphClient.java
/** * Modifies a graph on the server using a query. * /*from ww w. j a v a2 s . c o m*/ * @param graphURI The graph URI. * @param query A query, i.e. SPARQL 1.1 Update. * @param mediaType The the content type of the query. * @return {@code true} indicating that the graph was updated sucessfully, * otherwise {@code false}. * @throws IOException In case of an error. */ public boolean modifyGraph(final URI graphURI, final String query, final MediaType mediaType) throws IOException { final HttpPatch request = new HttpPatch(getGraphURI(graphURI)); final StringEntity entity = new StringEntity(query); // From the spec it's unclear if a media type is required // <http://www.w3.org/TR/2012/WD-sparql11-http-rdf-update-20120501/#http-patch> // Other methods do not require a media type and the server should guess it/assume a default // so we don't mandate a media type here. entity.setContentType(mediaType != null ? mediaType.toString() : null); request.setEntity(entity); final int status = getStatusCode(request); return status == 200 || status == 204; }
From source file:org.apache.olingo.server.example.TripPinServiceTest.java
@Test public void testUpdateEntity() throws Exception { String payload = "{" + " \"Emails\":[" + " \"Krista@example.com\"," + " \"Krista@gmail.com\"" + " ]" + "}"; HttpPatch updateRequest = new HttpPatch(baseURL + "/People('kristakemp')"); updateRequest.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); httpSend(updateRequest, 204);//from w ww.j a v a 2 s . co m HttpResponse response = httpGET(baseURL + "/People('kristakemp')", 200); JsonNode node = getJSONNode(response); assertEquals("$metadata#People/$entity", node.get("@odata.context").asText()); assertEquals("Krista@example.com", node.get("Emails").get(0).asText()); assertEquals("Krista@gmail.com", node.get("Emails").get(1).asText()); }
From source file:com.serena.rlc.provider.tfs.client.TFSClient.java
/** * Execute a patch request to TFS./*from w w w.j av a 2 s.c om*/ * * @param whichApi the API to use * @param path the path for the specific request * @param parameters parameters to send with the query * @param body the body to send with the request * @return String containing the response body * @throws TFSClientException */ public String processPatch(VisualStudioApi whichApi, String path, String parameters, String body) throws TFSClientException { String uri = createUrl(whichApi, path, parameters); logger.debug("Start executing TFS PATCH request to url=\"{}\" with data: {}", uri, body); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPatch patchRequest = new HttpPatch(uri); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getTFSUsername(), getTFSPassword()); patchRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false)); patchRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE); patchRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE); try { patchRequest.setEntity(new StringEntity(body, "UTF-8")); } catch (UnsupportedEncodingException ex) { logger.error(ex.getMessage(), ex); throw new TFSClientException("Error creating body for PATCH request", ex); } String result = ""; try { HttpResponse response = httpClient.execute(patchRequest); if (response.getStatusLine().getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_OK && response.getStatusLine() .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_CREATED && response.getStatusLine() .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_ACCEPTED) { throw createHttpError(response); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuilder sb = new StringBuilder(1024); String output; while ((output = br.readLine()) != null) { sb.append(output); } result = sb.toString(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new TFSClientException("Server not available", e); } logger.debug("End executing TFS PATCH request to url=\"{}\" and received this result={}", uri, result); return result; }
From source file:org.apache.sling.testing.clients.AbstractSlingClient.java
/** * <p>Executes a PATCH request and consumes the entity in the response. The content is cached and be retrieved by calling * {@code response.getContent()}</p> * * <p>Adds the passed entity and headers and checks the expected status</p> * * @param requestPath path relative to client url * @param entity the entity to be added to request * @param headers optional url parameters to be added * @param expectedStatus if passed, the response status will have to match one of them * @return the response with the entity consumed and the content cached * @throws ClientException if the request could not be executed *///from w ww .ja v a2s. co m public SlingHttpResponse doPatch(String requestPath, HttpEntity entity, List<Header> headers, int... expectedStatus) throws ClientException { HttpEntityEnclosingRequestBase request = new HttpPatch(getUrl(requestPath)); if (entity != null) { request.setEntity(entity); } return doRequest(request, headers, expectedStatus); }
From source file:org.elasticsearch.client.RestClient.java
private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) { switch (method.toUpperCase(Locale.ROOT)) { case HttpDeleteWithEntity.METHOD_NAME: return addRequestBody(new HttpDeleteWithEntity(uri), entity); case HttpGetWithEntity.METHOD_NAME: return addRequestBody(new HttpGetWithEntity(uri), entity); case HttpHead.METHOD_NAME: return addRequestBody(new HttpHead(uri), entity); case HttpOptions.METHOD_NAME: return addRequestBody(new HttpOptions(uri), entity); case HttpPatch.METHOD_NAME: return addRequestBody(new HttpPatch(uri), entity); case HttpPost.METHOD_NAME: HttpPost httpPost = new HttpPost(uri); addRequestBody(httpPost, entity); return httpPost; case HttpPut.METHOD_NAME: return addRequestBody(new HttpPut(uri), entity); case HttpTrace.METHOD_NAME: return addRequestBody(new HttpTrace(uri), entity); default://w w w.jav a2s. c o m throw new UnsupportedOperationException("http method not supported: " + method); } }
From source file:com.mxhero.plugin.cloudstorage.onedrive.api.Items.java
/** * Update item./*from w w w.j a v a2 s .co m*/ * * @param path the path * @param item the item * @return the item */ private Item updateItem(final String path, final Item item) { final Command<Item> command = commandFactory.create(); return command.excecute(new CommandHandler<Item>() { @Override public Item response(HttpResponse response) { try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return OneDrive.JACKSON.readValue(EntityUtils.toString(response.getEntity()), Item.class); } if (response.getStatusLine().getStatusCode() > 399) { throw new ApiException(response); } throw new IllegalArgumentException( "error reading response body with code " + response.getStatusLine().getStatusCode()); } catch (Exception e) { throw new IllegalArgumentException("error reading response", e); } } @Override public HttpUriRequest request() { HttpPatch httpPatch = new HttpPatch(command.baseUrl() + path); httpPatch.setHeader("Content-type", "application/json"); StringEntity entity; try { entity = new StringEntity(OneDrive.JACKSON.writeValueAsString(item), "UTF-8"); } catch (Exception e) { throw new IllegalArgumentException("error sending path for " + path, e); } httpPatch.setEntity(entity); return httpPatch; } }); }