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:com.sap.core.odata.fit.basic.RequestContentTypeTest.java

@Test
public void unsupportedContentTypeParameter() throws Exception {
    HttpPatch patch = new HttpPatch(URI.create(getEndpoint().toString() + "Rooms('1')"));
    patch.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.APPLICATION_JSON + ";illegal=wrong");
    final HttpResponse response = getHttpClient().execute(patch);
    assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(),
            response.getStatusLine().getStatusCode());
}

From source file:org.camunda.connect.httpclient.impl.AbstractHttpConnector.java

@SuppressWarnings("unchecked")
protected <T extends HttpRequestBase> T createHttpRequestBase(Q request) {
    String url = request.getUrl();
    if (url != null && !url.trim().isEmpty()) {
        String method = request.getMethod();
        if (HttpGet.METHOD_NAME.equals(method)) {
            return (T) new HttpGet(url);
        } else if (HttpPost.METHOD_NAME.equals(method)) {
            return (T) new HttpPost(url);
        } else if (HttpPut.METHOD_NAME.equals(method)) {
            return (T) new HttpPut(url);
        } else if (HttpDelete.METHOD_NAME.equals(method)) {
            return (T) new HttpDelete(url);
        } else if (HttpPatch.METHOD_NAME.equals(method)) {
            return (T) new HttpPatch(url);
        } else if (HttpHead.METHOD_NAME.equals(method)) {
            return (T) new HttpHead(url);
        } else if (HttpOptions.METHOD_NAME.equals(method)) {
            return (T) new HttpOptions(url);
        } else if (HttpTrace.METHOD_NAME.equals(method)) {
            return (T) new HttpTrace(url);
        } else {/*w  w  w.  j  av a 2  s . c om*/
            throw LOG.unknownHttpMethod(method);
        }
    } else {
        throw LOG.requestUrlRequired();
    }
}

From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java

public static int sendPATCH(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPatch httpPatch = new HttpPatch(endpoint);
    for (String headerType : headers.keySet()) {
        httpPatch.setHeader(headerType, headers.get(headerType));
    }/*from  ww w  . jav  a2s .  c  o  m*/
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPatch.setHeader("Content-Type", "application/json");
        }
        httpPatch.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPatch);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:com.github.tomakehurst.wiremock.http.HttpClientFactory.java

public static HttpUriRequest getHttpRequestFor(RequestMethod method, String url) {
    notifier().info("Proxying: " + method + " " + url);

    if (method.equals(GET))
        return new HttpGet(url);
    else if (method.equals(POST))
        return new HttpPost(url);
    else if (method.equals(PUT))
        return new HttpPut(url);
    else if (method.equals(DELETE))
        return new HttpDelete(url);
    else if (method.equals(HEAD))
        return new HttpHead(url);
    else if (method.equals(OPTIONS))
        return new HttpOptions(url);
    else if (method.equals(TRACE))
        return new HttpTrace(url);
    else if (method.equals(PATCH))
        return new HttpPatch(url);
    else// w  ww.  java 2 s  .c o  m
        return new GenericHttpUriRequest(method.toString(), url);
}

From source file:com.feedeo.rest.client.AbstractRestClient.java

protected ClientHttpRequestFactory createClientHttpRequestFactory(HttpClient httpClient) {
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override//from w  ww.ja  v a2  s  . c  o  m
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            switch (httpMethod) {
            case GET:
                return new HttpGet(uri);
            case DELETE:
                return new HttpEntityEnclosingDeleteRequest(uri);
            case HEAD:
                return new HttpHead(uri);
            case OPTIONS:
                return new HttpOptions(uri);
            case POST:
                return new HttpPost(uri);
            case PUT:
                return new HttpPut(uri);
            case TRACE:
                return new HttpTrace(uri);
            case PATCH:
                return new HttpPatch(uri);
            default:
                throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
            }
        }
    };
}

From source file:com.cloud.network.brocade.BrocadeVcsApi.java

protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException {
    String url;/*from ww w .  j a  v a  2 s .  c o m*/
    try {
        url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Brocade Switch API URL", e);
        throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new HttpPost(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new HttpGet(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new HttpDelete(url);
    } else if ("patch".equalsIgnoreCase(type)) {
        return new HttpPatch(url);
    } else {
        throw new BrocadeVcsApiException("Requesting unknown method type");
    }
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Patch response./*from  w w  w  .j  a  v a2s  .c  o  m*/
 *
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse patchResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpPatch httpPatch = new HttpPatch(url);
        httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPatch.setHeader(HttpHeaders.ACCEPT, "application/json");

        final StringEntity params = new StringEntity(json);
        httpPatch.setEntity(params);

        final CloseableHttpResponse response = httpClient.execute(httpPatch);
        setLogString("Status == " + response.getStatusLine(), true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}

From source file:com.lovebridge.library.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from   ww  w. j  a  va2  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());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    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: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.
 *//*from  w w w  .ja va  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:ch.cyberduck.core.googledrive.DriveWriteFeature.java

@Override
public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    final DelayedHttpEntityCallable<Void> command = new DelayedHttpEntityCallable<Void>() {
        @Override//from   w  w  w. j a v a 2s . co  m
        public Void call(final AbstractHttpEntity entity) throws BackgroundException {
            try {
                final String base = session.getClient().getRootUrl();
                // Initiate a resumable upload
                final HttpEntityEnclosingRequestBase request;
                if (status.isExists()) {
                    final String fileid = new DriveFileidProvider(session).getFileid(file,
                            new DisabledListProgressListener());
                    request = new HttpPatch(
                            String.format("%s/upload/drive/v3/files/%s?supportsTeamDrives=true", base, fileid));
                    if (StringUtils.isNotBlank(status.getMime())) {
                        request.setHeader(HttpHeaders.CONTENT_TYPE, status.getMime());
                    }
                    // Upload the file
                    request.setEntity(entity);
                } else {
                    request = new HttpPost(String.format(
                            String.format(
                                    "%%s/upload/drive/v3/files?uploadType=resumable&supportsTeamDrives=%s",
                                    PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")),
                            base));
                    request.setEntity(new StringEntity(
                            "{\"name\": \"" + file.getName() + "\", \"parents\": [\""
                                    + new DriveFileidProvider(session).getFileid(file.getParent(),
                                            new DisabledListProgressListener())
                                    + "\"]}",
                            ContentType.create("application/json", "UTF-8")));
                    if (StringUtils.isNotBlank(status.getMime())) {
                        // Set to the media MIME type of the upload data to be transferred in subsequent requests.
                        request.addHeader("X-Upload-Content-Type", status.getMime());
                    }
                }
                request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
                final HttpClient client = session.getHttpClient();
                final HttpResponse response = client.execute(request);
                try {
                    switch (response.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_OK:
                        break;
                    default:
                        throw new DriveExceptionMappingService()
                                .map(new HttpResponseException(response.getStatusLine().getStatusCode(),
                                        response.getStatusLine().getReasonPhrase()));
                    }
                } finally {
                    EntityUtils.consume(response.getEntity());
                }
                if (!status.isExists()) {
                    if (response.containsHeader(HttpHeaders.LOCATION)) {
                        final String putTarget = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
                        // Upload the file
                        final HttpPut put = new HttpPut(putTarget);
                        put.setEntity(entity);
                        final HttpResponse putResponse = client.execute(put);
                        try {
                            switch (putResponse.getStatusLine().getStatusCode()) {
                            case HttpStatus.SC_OK:
                            case HttpStatus.SC_CREATED:
                                break;
                            default:
                                throw new DriveExceptionMappingService().map(
                                        new HttpResponseException(putResponse.getStatusLine().getStatusCode(),
                                                putResponse.getStatusLine().getReasonPhrase()));
                            }
                        } finally {
                            EntityUtils.consume(putResponse.getEntity());
                        }
                    } else {
                        throw new DriveExceptionMappingService()
                                .map(new HttpResponseException(response.getStatusLine().getStatusCode(),
                                        response.getStatusLine().getReasonPhrase()));
                    }
                }
                return null;
            } catch (IOException e) {
                throw new DriveExceptionMappingService().map("Upload failed", e, file);
            }
        }

        @Override
        public long getContentLength() {
            return status.getLength();
        }
    };
    return this.write(file, status, command);
}