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.googlesource.gerrit.plugins.its.rtc.network.Transport.java

public <T> T patch(final String path, final Type typeOrClass, JsonObject data, String etag) throws IOException {
    HttpPatch request = newHttpPatch(path);
    if (log.isDebugEnabled())
        log.debug("Preparing PATCH against " + request.getURI() + " using etag " + etag + " and data " + data);
    request.setEntity(new StringEntity(data.toString(), StandardCharsets.UTF_8));
    if (etag != null)
        request.addHeader("If-Match", etag);
    return invoke(request, typeOrClass, APP_OSLC, APP_OSLC);
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.Transport.java

public <T> T patch(final String path, final Type typeOrClass, JsonObject data, String etag) throws IOException {
    HttpPatch request = newHttpPatch(path);
    if (log.isDebugEnabled())
        log.debug("Preparing PATCH against " + request.getURI() + " using etag " + etag + " and data " + data);
    request.setEntity(new StringEntity(data.toString(), HTTP.UTF_8));
    if (etag != null)
        request.addHeader("If-Match", etag);
    return invoke(request, typeOrClass, APP_OSLC, APP_OSLC);
}

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

/**
 * Make a PATCH request/* w  w  w .  ja  va  2 s.co 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:org.callimachusproject.test.WebResource.java

public void patch(String type, byte[] body) throws IOException {
    ByteArrayEntity entity = new ByteArrayEntity(body);
    entity.setContentType(type);//  w  w  w  . ja va  2  s  .c  o  m
    HttpPatch req = new HttpPatch(uri);
    req.setEntity(entity);
    DefaultHttpClient client = new DefaultHttpClient();
    URL url = req.getURI().toURL();
    int port = url.getPort();
    String host = url.getHost();
    PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication(url.getHost(),
            InetAddress.getByName(url.getHost()), port, url.getProtocol(), "", "digest", url,
            RequestorType.SERVER);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(passAuth.getUserName(),
            new String(passAuth.getPassword()));
    client.getCredentialsProvider().setCredentials(new AuthScope(host, port), credentials);
    client.execute(req, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine status = response.getStatusLine();
            int code = status.getStatusCode();
            if (code != 200 && code != 204) {
                Assert.assertEquals(status.getReasonPhrase(), 204, code);
            }
            return null;
        }
    });
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java

void update(SObject sObject) throws IOException {
    HttpPatch patch = new HttpPatch(getUri("/sobjects/" + sObject.getType() + "/" + sObject.getId()));
    patch.setEntity(getEntityForSObjectFieldsJson(sObject));
    patch.addHeader("Content-Type", UPLOAD_CONTENT_TYPE);

    executeRequestForString(patch);//w w w.ja v a2s .co  m
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;/* w ww .  j av a 2 s.c om*/
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:com.kixeye.relax.AsyncRestClient.java

/**
 * @see com.kixeye.relax.RestClient#patch(java.lang.String, java.lang.String, java.lang.String, I, java.lang.Object)
 *///from   w w w  .ja va  2s. c om
@Override
public <I> HttpPromise<HttpResponse<Void>> patch(String path, String contentTypeHeader, String acceptHeader,
        I requestObject, Map<String, List<String>> additonalHeaders, Object... pathVariables)
        throws IOException {
    HttpPromise<HttpResponse<Void>> promise = new HttpPromise<>();

    HttpPatch request = new HttpPatch(UrlUtils.expand(uriPrefix + path, pathVariables));
    if (requestObject != null) {
        request.setEntity(new ByteArrayEntity(serDe.serialize(contentTypeHeader, requestObject)));
    }

    if (contentTypeHeader != null) {
        request.setHeader("Content-Type", contentTypeHeader);
    }

    if (acceptHeader != null) {
        request.setHeader("Accept", acceptHeader);
    }

    if (additonalHeaders != null && !additonalHeaders.isEmpty()) {
        for (Entry<String, List<String>> header : additonalHeaders.entrySet()) {
            for (String value : header.getValue()) {
                request.addHeader(header.getKey(), value);
            }
        }
    }

    httpClient.execute(request, new AsyncRestClientResponseCallback<>(null, promise));

    return promise;
}

From source file:com.microsoft.projectoxford.face.rest.WebServiceRequest.java

private Object patch(String url, Map<String, Object> data, String contentType)
        throws ClientException, IOException {
    HttpPatch request = new HttpPatch(url);
    request.setHeader(HEADER_KEY, mSubscriptionKey);
    String json = mGson.toJson(data).toString();
    StringEntity entity = new StringEntity(json);
    request.setEntity(entity);
    request.setHeader(CONTENT_TYPE, APPLICATION_JSON);
    HttpResponse response = mClient.execute(request);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        return readInput(response.getEntity().getContent());
    } else {/* w  w  w .j a va  2s  .  c om*/
        json = readInput(response.getEntity().getContent());
        if (json != null) {
            ServiceError error = mGson.fromJson(json, ServiceError.class);
            if (error != null) {
                throw new ClientException(error.error);
            }
        }

        throw new ClientException("Error executing Patch request!", statusCode);
    }
}

From source file:org.fcrepo.integration.connector.file.FileConnectorIT.java

/**
 * I should be able to link to content on a federated filesystem.
 *
 * @throws IOException thrown during this function
 **//*from w w w . j  a  v  a 2 s  . com*/
@Test
public void testFederatedDatastream() throws IOException {
    final String federationAddress = serverAddress + "files/FileSystem1/ds1";
    final String linkingAddress;
    try (final CloseableHttpResponse response = client.execute(new HttpPost(serverAddress))) {
        EntityUtils.consume(response.getEntity());
        linkingAddress = response.getFirstHeader("Location").getValue();
    }

    // link from the object to the content of the file on the federated filesystem
    final HttpPatch patch = new HttpPatch(linkingAddress);
    patch.addHeader("Content-Type", "application/sparql-update");
    patch.setEntity(new ByteArrayEntity(("INSERT DATA { <> <http://some-vocabulary#hasExternalContent> " + "<"
            + federationAddress + "> . }").getBytes()));
    assertEquals("Couldn't link to external datastream!", NO_CONTENT.getStatusCode(), getStatus(patch));
}

From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java

protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity,
        MultiValueMap<String, String> headers, MultiValueMap<String, String> params) {
    HttpRequest httpRequest;//  w w  w.  j  a va 2s .com

    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    case "DELETE":
        BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb,
                uri + this.helper.getQueryString(params));
        httpRequest = entityRequest;
        entityRequest.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }

    httpRequest.setHeaders(convertHeaders(headers));
    return httpRequest;
}