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

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

Introduction

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

Prototype

public HttpPatch(final String uri) 

Source Link

Usage

From source file:info.androidhive.volleyjson.util.SslHttpStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//* www .  j  a  v a 2  s .  c om*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        //setMultiPartBody(postRequest,request);
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        //setMultiPartBody(putRequest,request);
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    // Added in source code of Volley libray.
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.fcrepo.camel.FedoraClient.java

/**
 * Make a PATCH request//from   ww w  . jav a  2  s  . c o m
 */
public FedoraResponse patch(final URI url, final String body)
        throws ClientProtocolException, IOException, HttpOperationFailedException {

    final HttpPatch request = new HttpPatch(url);
    request.addHeader("Content-Type", "application/sparql-update");
    if (body != null) {
        request.setEntity(new StringEntity(body));
    }

    final HttpResponse response = httpclient.execute(request);
    final int status = response.getStatusLine().getStatusCode();
    final String contentType = getContentTypeHeader(response);

    if ((status >= 200 && status < 300) || !this.throwExceptionOnFailure) {
        final HttpEntity entity = response.getEntity();
        return new FedoraResponse(url, status, contentType, null,
                entity != null ? EntityUtils.toString(entity) : null);
    } else {
        throw buildHttpOperationFailedException(url, response);
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpDownloader.java

public final DownloadItem request(final URI uri, final Method method, final CredentialItem credentialItem,
        final List<Header> additionalHeaders, final List<CookieItem> cookies, final HttpEntity entity)
        throws ClientProtocolException, IllegalStateException, IOException, URISyntaxException,
        SearchLibException {//from ww w.j  a va  2  s.  c om
    HttpRequestBase httpRequestBase;
    switch (method) {
    case GET:
        httpRequestBase = new HttpGet(uri);
        break;
    case POST:
        httpRequestBase = new HttpPost(uri);
        break;
    case PUT:
        httpRequestBase = new HttpPut(uri);
        break;
    case DELETE:
        httpRequestBase = new HttpDelete(uri);
        break;
    case OPTIONS:
        httpRequestBase = new HttpOptions(uri);
        break;
    case PATCH:
        httpRequestBase = new HttpPatch(uri);
        break;
    case HEAD:
        httpRequestBase = new HttpHead(uri);
        break;
    default:
        throw new SearchLibException("Unkown method: " + method);
    }
    return request(httpRequestBase, credentialItem, additionalHeaders, cookies, entity);
}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpClient.java

/**
 * Send a HTTP PATCH request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response//from w ww .  j a  v  a2s  .c om
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPatch(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPatch(url);
    setHeaders(headers, request);
    return client.execute(request);
}

From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java

/**
 * Send a HTTP PATCH request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response//from  w ww.  j ava 2 s  .c o  m
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPatch(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPatch(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

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

public WireMockResponse patchWithBody(String url, String body, String contentType, TestHttpHeader... headers) {
    HttpPatch httpPatch = new HttpPatch(mockServiceUrlFor(url));
    return requestWithBody(httpPatch, body, contentType, headers);
}

From source file:com.ring.ytjojo.ssl.SslHttpStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*w  w  w.j  a  v a 2 s  .co m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(postRequest, request);
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(putRequest, request);
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    // Added in source code of Volley libray.
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.r10r.doctester.testbrowser.TestBrowserImpl.java

private Response makePatchPostOrPutRequest(Request httpRequest) {

    org.apache.http.HttpResponse apacheHttpClientResponse;
    Response response = null;//from  w w w.j  ava  2 s  .c o m

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpEntityEnclosingRequestBase apacheHttpRequest;

        if (PATCH.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPatch(httpRequest.uri);

        } else if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPost(httpRequest.uri);

        } else {

            apacheHttpRequest = new HttpPut(httpRequest.uri);
        }

        if (httpRequest.headers != null) {
            // add all headers
            for (Entry<String, String> header : httpRequest.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        ///////////////////////////////////////////////////////////////////
        // Either add form parameters...
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.formParameters != null) {

            List<BasicNameValuePair> formparams = Lists.newArrayList();
            for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) {

                formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
            }

            // encode form parameters and add
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add multipart file upload
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.filesToUpload != null) {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) {

                // For File parameters
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));

            }

            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add payload and convert if Json or Xml
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.payload != null) {

            if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) {

                String string = new ObjectMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType("application/json; charset=utf-8");

                apacheHttpRequest.setEntity(entity);

            } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) {

                String string = new XmlMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8);

                apacheHttpRequest.setEntity(new StringEntity(string, "utf-8"));

            } else if (httpRequest.payload instanceof String) {

                StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8");
                apacheHttpRequest.setEntity(entity);

            } else {

                StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8");
                apacheHttpRequest.setEntity(entity);

            }

        }

        setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects);

        // Here we go!
        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);
        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        apacheHttpRequest.releaseConnection();

    } catch (IOException e) {
        logger.error("Fatal problem creating PATCH, POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java

/**
 * Create the HTTP Method./*from   ww  w  . j a  va 2 s.  c  o  m*/
 * @return the method
 */
private HttpUriRequest createMethod() {
    HttpUriRequest request = null;

    switch (mMethod) {
    case GET:
        request = new HttpGet(mUrl);
        break;

    case POST:
        request = new HttpPost(mUrl);
        break;

    case PATCH:
        request = new HttpPatch(mUrl);
        break;

    case OPTIONS:
        request = new HttpOptions(mUrl);
        break;

    case DELETE:
        request = new HttpDelete(mUrl);
        break;

    case PUT:
        request = new HttpPut(mUrl);
        break;

    case HEAD:
        request = new HttpHead(mUrl);
        break;

    case TRACE:
        request = new HttpTrace(mUrl);
        break;

    default:
        throw new UnsupportedOperationException("Unknown method: " + mMethod.toString());
    }

    return request;
}

From source file:org.wso2.am.integration.tests.other.HttpPATCHSupportTestCase.java

@Test(groups = "wso2.am", description = "Check functionality of HTTP PATCH support for APIM")
public void testHttpPatchSupport() throws Exception {
    //Login to the API Publisher
    apiPublisher.login(user.getUserName(), user.getPassword());

    String APIName = "HttpPatchAPI";
    String APIContext = "patchTestContext";
    String url = getGatewayURLNhttp() + "httpPatchSupportContext";
    String providerName = user.getUserName();
    String APIVersion = "1.0.0";

    APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
    apiRequest.setVersion(APIVersion);// w w w . ja  v  a2s  . c om
    apiRequest.setProvider(providerName);

    //Adding the API to the publisher
    apiPublisher.addAPI(apiRequest);

    //Publish the API
    APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName,
            APILifeCycleState.PUBLISHED);
    apiPublisher.changeAPILifeCycleStatus(updateRequest);

    String modifiedResource = "{\"paths\":{ \"/*\":{\"patch\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\","
            + "\"x-throttling-tier\":\"Unlimited\" },\"get\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\","
            + "\"x-throttling-tier\":\"Unlimited\",\"x-scope\":\"user_scope\"}}},\"swagger\":\"2.0\",\"info\":{\"title\":\"HttpPatchAPI\",\"version\":\"1.0.0\"},"
            + "\"x-wso2-security\":{\"apim\":{\"x-wso2-scopes\":[{\"name\":\"admin_scope\",\"description\":\"\",\"key\":\"admin_scope\",\"roles\":\"admin\"},"
            + "{\"name\":\"user_scope\",\"description\":\"\",\"key\":\"user_scope\",\"roles\":\"admin,subscriber\"}]}}}";

    //Modify the resources to add the PATCH resource method to the API
    apiPublisher.updateResourceOfAPI(providerName, APIName, APIVersion, modifiedResource);

    //Login to the API Store
    apiStore.login(user.getUserName(), user.getPassword());

    //Add an Application in the Store.
    apiStore.addApplication("HttpPatchSupportAPP", APIMIntegrationConstants.APPLICATION_TIER.LARGE, "",
            "Test-HTTP-PATCH");

    //Subscribe to the new application
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, APIVersion, providerName,
            "HttpPatchSupportAPP", APIMIntegrationConstants.API_TIER.GOLD);
    apiStore.subscribe(subscriptionRequest);

    //Generate a production token and invoke the API
    APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("HttpPatchSupportAPP");
    String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
    JSONObject jsonResponse = new JSONObject(responseString);

    //Get the accessToken generated.
    String accessToken = jsonResponse.getJSONObject("data").getJSONObject("key").getString("accessToken");

    String apiInvocationUrl = getAPIInvocationURLHttp(APIContext, APIVersion);

    //Invoke the API by sending a PATCH request;

    HttpClient client = HttpClientBuilder.create().build();
    HttpPatch request = new HttpPatch(apiInvocationUrl);
    request.setHeader("Accept", "application/json");
    request.setHeader("Authorization", "Bearer " + accessToken);
    StringEntity payload = new StringEntity("{\"first\":\"Greg\"}", "UTF-8");
    payload.setContentType("application/json");
    request.setEntity(payload);

    HttpResponse httpResponsePatch = client.execute(request);

    //Assertion
    assertEquals(httpResponsePatch.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(),
            "The response code is not 200 OK");

}