Example usage for org.apache.http.client.methods HttpPatch setEntity

List of usage examples for org.apache.http.client.methods HttpPatch setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPatch setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.messagemedia.restapi.client.v1.internal.RestRequest.java

/**
 * Builds an apache http request//  w  ww .ja v a  2 s.co  m
 *
 * @return the apache http request
 */
HttpUriRequest getHttpRequest() {
    HttpUriRequest request;
    switch (method) {
    case GET:
        request = new HttpGet(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        post.setEntity(new ByteArrayEntity(body));
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        put.setEntity(new ByteArrayEntity(body));
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        patch.setEntity(new ByteArrayEntity(body));
        request = patch;
        break;
    default:
        throw new RuntimeException("Method not supported");
    }

    addHeaders(request);

    return request;
}

From source file:com.microsoft.services.odata.unittests.testsupport.WireMockTestClient.java

public WireMockResponse patch(String url, HttpEntity entity) {
    HttpPatch httpPatch = new HttpPatch(mockServiceUrlFor(url));
    httpPatch.setEntity(entity);
    return executeMethodAndCovertExceptions(httpPatch);
}

From source file:org.datagator.api.client.backend.DataGatorService.java

public CloseableHttpResponse patch(String endpoint, InputStream data, ContentType ctype)
        throws URISyntaxException, IOException {
    HttpPatch request = new HttpPatch(buildServiceURI(endpoint));
    if (data != null) {
        HttpEntity entity = new InputStreamEntity(data, ctype);
        request.setEntity(entity);
    }//  w  w w.j  av a  2s . c o  m
    return http.execute(request, context);
}

From source file:com.meplato.store2.ApacheHttpClient.java

/**
 * Execute runs a HTTP request/response with an API endpoint.
 *
 * @param method      the HTTP method, e.g. POST or GET
 * @param uriTemplate the URI template according to RFC 6570
 * @param parameters  the query string parameters
 * @param headers     the key/value pairs for the HTTP header
 * @param body        the body of the request or {@code null}
 * @return the HTTP response encapsulated by {@link Response}.
 * @throws ServiceException if e.g. the service is unavailable.
 *///  ww  w  .  j av  a  2s.  c o  m
@Override
public Response execute(String method, String uriTemplate, Map<String, Object> parameters,
        Map<String, String> headers, Object body) throws ServiceException {
    // URI template parameters
    String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters);

    // Body
    HttpEntity requestEntity = null;
    if (body != null) {
        Gson gson = getSerializer();
        try {
            requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8")
                    .setContentType(ContentType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new ServiceException("Error serializing body", null, e);
        }
    }

    // Do HTTP request
    HttpRequestBase httpRequest = null;
    if (method.equalsIgnoreCase("GET")) {
        httpRequest = new HttpGet(url);
    } else if (method.equalsIgnoreCase("POST")) {
        HttpPost httpPost = new HttpPost(url);
        if (requestEntity != null) {
            httpPost.setEntity(requestEntity);
        }
        httpRequest = httpPost;
    } else if (method.equalsIgnoreCase("PUT")) {
        HttpPut httpPut = new HttpPut(url);
        if (requestEntity != null) {
            httpPut.setEntity(requestEntity);
        }
        httpRequest = httpPut;
    } else if (method.equalsIgnoreCase("DELETE")) {
        httpRequest = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("PATCH")) {
        HttpPatch httpPatch = new HttpPatch(url);
        if (requestEntity != null) {
            httpPatch.setEntity(requestEntity);
        }
        httpRequest = httpPatch;
    } else if (method.equalsIgnoreCase("HEAD")) {
        httpRequest = new HttpHead(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        httpRequest = new HttpOptions(url);
    } else {
        throw new ServiceException("Invalid HTTP method: " + method, null, null);
    }

    // Headers
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }
    httpRequest.setHeader("Accept", "application/json");
    httpRequest.setHeader("Accept-Charset", "utf-8");
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");
    httpRequest.setHeader("User-Agent", USER_AGENT);

    try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
        Response response = new ApacheHttpResponse(httpResponse);
        int statusCode = response.getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            return response;
        }
        throw ServiceException.fromResponse(response);
    } catch (ClientProtocolException e) {
        throw new ServiceException("Client Protocol Exception", null, e);
    } catch (IOException e) {
        throw new ServiceException("IO Exception", null, e);
    }
}

From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java

public WireMockResponse patch(String url, HttpEntity entity) {
    HttpPatch httpPatch = new HttpPatch(mockServiceUrlFor(url));
    httpPatch.setEntity(entity);
    return executeMethodAndConvertExceptions(httpPatch);
}

From source file:de.yaio.commons.http.HttpUtils.java

/** 
 * execute POST-Request for url with params
 * @param baseUrl                the url to call
 * @param username               username for auth
 * @param password               password for auth
 * @param params                 params for the request
 * @param textFileParams         text-files to upload
 * @param binFileParams          bin-files to upload
 * @return                       HttpResponse
 * @throws IOException           possible Exception if Request-state <200 > 299 
 *//*from   w  w  w . j  a  v a 2  s  .co m*/
public static HttpResponse callPatchUrlPure(final String baseUrl, final String username, final String password,
        final Map<String, String> params, final Map<String, String> textFileParams,
        final Map<String, String> binFileParams) throws IOException {
    // create request
    HttpPatch request = new HttpPatch(baseUrl);

    // map params
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (MapUtils.isNotEmpty(params)) {
        for (String key : params.keySet()) {
            builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
        }
    }

    // map files
    if (MapUtils.isNotEmpty(textFileParams)) {
        for (String key : textFileParams.keySet()) {
            File file = new File(textFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key));
        }
    }
    // map files
    if (MapUtils.isNotEmpty(binFileParams)) {
        for (String key : binFileParams.keySet()) {
            File file = new File(binFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key));
        }
    }

    // set request
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);

    // add request header
    request.addHeader("User-Agent", "YAIOCaller");

    // call url
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending 'PATCH' request to URL : " + baseUrl);
    }
    HttpResponse response = executeRequest(request, username, password);

    // get response
    int retCode = response.getStatusLine().getStatusCode();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Response Code : " + retCode);
    }
    return response;
}

From source file:org.frontcache.hystrix.FC_BypassCache.java

/**
 * forward all kind of requests (GET, POST, PUT, ...)
 * /*  w w w . j a  v  a  2s .c o  m*/
 * @param httpclient
 * @param verb
 * @param uri
 * @param request
 * @param headers
 * @param params
 * @param requestEntity
 * @return
 * @throws Exception
 */
private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        Map<String, List<String>> headers, InputStream requestEntity) throws Exception {

    URL host = context.getOriginURL();
    HttpHost httpHost = FCUtils.getHttpHost(host);
    uri = (host.getPath() + uri).replaceAll("/{2,}", "/");

    HttpRequest httpRequest;
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + context.getRequestQueryString());
        httpRequest = httpPost;
        httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + context.getRequestQueryString());
        httpRequest = httpPut;
        httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + context.getRequestQueryString());
        httpRequest = httpPatch;
        httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + context.getRequestQueryString());
    }

    try {
        httpRequest.setHeaders(FCUtils.convertHeaders(headers));
        Header acceptEncoding = httpRequest.getFirstHeader("accept-encoding");
        if (acceptEncoding != null && acceptEncoding.getValue().contains("gzip")) {
            httpRequest.setHeader("accept-encoding", "gzip");
        }
        HttpResponse originResponse = httpclient.execute(httpHost, httpRequest);
        return originResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.infinities.keystone4j.PatchClient.java

public JsonNode connect(Object obj) throws ClientProtocolException, IOException {
    String input = JsonUtils.toJsonWithoutPrettyPrint(obj);
    logger.debug("input: {}", input);
    StringEntity requestEntity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from w w w .  j  ava2s  .  c  o  m*/
        HttpPatch request = new HttpPatch(url);
        request.addHeader("accept", "application/json");
        request.addHeader("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText());
        request.setEntity(requestEntity);
        ResponseHandler<JsonNode> rh = new ResponseHandler<JsonNode>() {

            @Override
            public JsonNode handleResponse(final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                String output = getStringFromInputStream(entity.getContent());
                logger.debug("output: {}", output);
                assertEquals(200, statusLine.getStatusCode());

                JsonNode node = JsonUtils.convertToJsonNode(output);
                return node;
            }

            private String getStringFromInputStream(InputStream is) {

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {

                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return sb.toString();

            }
        };
        JsonNode node = httpclient.execute(request, rh);

        return node;
    } finally {
        httpclient.close();
    }
}

From source file:org.fcrepo.integration.rdf.ServerManagedTriplesIT.java

private CloseableHttpResponse performUpdate(final String pid, final String updateString) throws Exception {
    final HttpPatch patchProp = patchObjMethod(pid);
    patchProp.setHeader(CONTENT_TYPE, "application/sparql-update");
    patchProp.setEntity(new StringEntity(updateString));
    return execute(patchProp);
}

From source file:com.getblimp.api.client.Blimp.java

public String patch(String resourceUri, BlimpObject data) {
    logger.fine("Entering Blimp.update method.");

    // Response output variable
    String output = null;// w ww.ja  v  a  2  s .  c o  m

    try {

        HttpPatch tmpPatch = (HttpPatch) createRequestMethod(createRequestUrl(resourceUri), HttpMethods.PATCH);

        tmpPatch.setEntity(createStringEntity(data));

        output = execute(tmpPatch);

    } catch (UnsupportedEncodingException e) {
        errorHandler(e);
    } catch (ClientProtocolException e) {
        errorHandler(e);
    } catch (IOException e) {
        errorHandler(e);
    } catch (Exception e) {
        errorHandler(e);
    }

    logger.fine("Blimp.update output: " + output);
    return output;
}