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.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  v a 2 s. c o  m*/
@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: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  va 2  s . com*/
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.fcrepo.integration.AbstractResourceIT.java

protected static void addMixin(final String pid, final String mixinUrl) throws IOException {
    final HttpPatch updateObjectGraphMethod = new HttpPatch(serverAddress + pid);
    updateObjectGraphMethod.addHeader(CONTENT_TYPE, "application/sparql-update");
    final BasicHttpEntity e = new BasicHttpEntity();

    e.setContent(new ByteArrayInputStream(
            ("INSERT DATA { <> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <" + mixinUrl + "> . } ")
                    .getBytes()));// ww  w . j  a va  2s  .co m
    updateObjectGraphMethod.setEntity(e);
    final HttpResponse response = client.execute(updateObjectGraphMethod);
    assertEquals(NO_CONTENT.getStatusCode(), response.getStatusLine().getStatusCode());
}

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

private HttpRequestBase createRequestMethod(String url, HttpMethods method) throws Exception {
    logger.fine("Entering Blimp.createRequestMethod");
    logger.finer("HTTP method: " + method.toString());

    HttpRequestBase tmpRequest;/*  www .ja va2 s .  c o m*/

    switch (method) {
    case GET:
        tmpRequest = new HttpGet(url);
        break;
    case POST:
        tmpRequest = new HttpPost(url);
        break;
    case PUT:
        tmpRequest = new HttpPut(url);
        break;
    case PATCH:
        tmpRequest = new HttpPatch(url);
        break;
    default:
        throw new Exception("Wrong HTTP method.");
    }
    logger.finer("Adding request headers");
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.AUTHORIZATION.getValue()),
            "ApiKey " + this.userName + ":" + this.apiKey);
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.APPID.getValue()), this.applicationId);
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.APPSECRET.getValue()),
            this.applicationSecret);

    logger.finer("Created request method: " + tmpRequest.getMethod());
    return tmpRequest;
}

From source file:wercker4j.request.RequestBuilder.java

/**
 * patch will call token API to update/*from   w  w  w . j a v a  2  s .com*/
 *
 * @param option option to call update token API
 * @return responseWrapper
 * @throws Wercker4jException fault statusCode and IO error
 */
public ResponseWrapper patch(UpdateTokenOption option) throws Wercker4jException {
    String url = UriTemplate.fromTemplate(endpoint + "/tokens{/tokenId}").set("tokenId", option.tokenId)
            .expand();
    HttpPatch httpPatch = new HttpPatch(url);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    try {
        httpPatch.setEntity(new StringEntity(mapper.writeValueAsString(option), "UTF-8"));
        return callPatchAPI(httpPatch);
    } catch (Exception e) {
        throw new Wercker4jException(e);
    }
}

From source file:org.fcrepo.integration.AbstractResourceIT.java

protected HttpResponse setProperty(final String pid, final String txId, final String propertyUri,
        final String value) throws IOException {
    final HttpPatch postProp = new HttpPatch(serverAddress + (txId != null ? txId + "/" : "") + pid);
    postProp.setHeader(CONTENT_TYPE, "application/sparql-update");
    final String updateString = "INSERT { <" + serverAddress + pid + "> <" + propertyUri + "> \"" + value
            + "\" } WHERE { }";
    postProp.setEntity(new StringEntity(updateString));
    final HttpResponse dcResp = execute(postProp);
    assertEquals(dcResp.getStatusLine().toString(), 204, dcResp.getStatusLine().getStatusCode());
    postProp.releaseConnection();/*w w  w  . j  a v  a 2 s . c  o m*/
    return dcResp;
}

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

private static int sendPATCH(String endpoint, String content, String acceptType) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPatch httpPatch = new HttpPatch(endpoint);
    httpPatch.setHeader("Accept", acceptType);
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        httpPatch.setHeader("Content-Type", "application/json");
        httpPatch.setEntity(httpEntity);
    }//from w w w .  j a v a 2 s  .c  o  m
    HttpResponse httpResponse = httpClient.execute(httpPatch);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse updateStack(String stackName, String stackUuid, String template)
        throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpPatch updateStack = null;/*from  w w  w . j av  a2s . c  o m*/
    HttpResponse response = null;

    String jsonTemplate = JavaStackUtils.convertYamlToJson(template);
    JSONObject modifiedObject = new JSONObject();
    modifiedObject.put("stack_name", stackName);
    modifiedObject.put("template", new JSONObject(jsonTemplate));

    if (this.isAuthenticated) {
        Logger.debug("");
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(this.endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.HEAT_PORT.toString());
        buildUrl.append(String.format("/%s/%s/stacks/%s/%s", Constants.HEAT_VERSION.toString(), tenant_id,
                stackName, stackUuid));

        // Logger.debug(buildUrl.toString());
        updateStack = new HttpPatch(buildUrl.toString());
        updateStack.setEntity(new StringEntity(modifiedObject.toString(), ContentType.APPLICATION_JSON));
        // Logger.debug(this.token_id);
        updateStack.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        Logger.debug("Request: " + updateStack.toString());
        Logger.debug("Request body: " + modifiedObject.toString());

        response = httpClient.execute(updateStack);
        int statusCode = response.getStatusLine().getStatusCode();
        String responsePhrase = response.getStatusLine().getReasonPhrase();

        Logger.debug("Response: " + response.toString());
        Logger.debug("Response body:");

        if (statusCode != 202) {
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = null;

            while ((line = in.readLine()) != null)
                Logger.debug(line);
        }

        return (statusCode == 202) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode,
                        responsePhrase + ". Create Failed with Status: " + statusCode), null);
    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }
}

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;// ww  w  .java 2 s  .co m
    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:de.taimos.httputils.HTTPRequest.java

/**
 * @param executor Thread pool//  www .j  a va  2  s. co  m
 * @param callback {@link HTTPResponseCallback}
 */
public void patchAsync(final Executor executor, final HTTPResponseCallback callback) {
    this.executeAsync(executor, new HttpPatch(this.buildURI()), callback);
}