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.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Perform a HTTP PATCH request and track the Android Context which
 * initiated the request./*from  ww w .  j a v  a2s  .c o  m*/
 * 
 * @param context
 *            the Android Context which initiated the request.
 * @param url
 *            the URL to send the request to.
 * @param entity
 *            a raw {@link HttpEntity} to send with the request, for
 *            example, use this to send string/json/xml payloads to a server
 *            by passing a {@link org.apache.http.entity.StringEntity}.
 * @param contentType
 *            the content type of the payload you are sending, for example
 *            application/json if sending a json payload.
 * @param responseHandler
 *            the response handler instance that should handle the response.
 */
public void patch(Context context, String url, HttpEntity entity, String contentType,
        AsyncHttpResponseHandler responseHandler) {
    sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPatch(url), entity), contentType,
            responseHandler, context);
}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Perform a HTTP PATCH request and track the Android Context which
 * initiated the request. Set headers only for this request
 * //from  www  .j a  va 2 s . c  o m
 * @param context
 *            the Android Context which initiated the request.
 * @param url
 *            the URL to send the request to.
 * @param headers
 *            set headers only for this request
 * @param params
 *            additional PATCH parameters to send with the request.
 * @param contentType
 *            the content type of the payload you are sending, for example
 *            application/json if sending a json payload.
 * @param responseHandler
 *            the response handler instance that should handle the response.
 */
public void patch(Context context, String url, Header[] headers, RequestParams params, String contentType,
        AsyncHttpResponseHandler responseHandler) {
    HttpEntityEnclosingRequestBase request = new HttpPatch(url);
    if (params != null)
        request.setEntity(paramsToEntity(params));
    if (headers != null)
        request.setHeaders(headers);
    sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Perform a HTTP PATCH request and track the Android Context which
 * initiated the request. Set headers only for this request
 * // w  ww . j  a v  a2s  . c  o  m
 * @param context
 *            the Android Context which initiated the request.
 * @param url
 *            the URL to send the request to.
 * @param headers
 *            set headers only for this request
 * @param entity
 *            a raw {@link HttpEntity} to send with the request, for
 *            example, use this to send string/json/xml payloads to a server
 *            by passing a {@link org.apache.http.entity.StringEntity}.
 * @param contentType
 *            the content type of the payload you are sending, for example
 *            application/json if sending a json payload.
 * @param responseHandler
 *            the response handler instance that should handle the response.
 */
public void patch(Context context, String url, Header[] headers, HttpEntity entity, String contentType,
        AsyncHttpResponseHandler responseHandler) {
    HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPatch(url), entity);
    if (headers != null)
        request.setHeaders(headers);
    sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}

From source file:net.packet.impl.PacketClient.java

private HttpUriRequest createHttpRequest(Request req) {
    try {//from   www.  j  ava  2 s .c o  m
        switch (req.getMethod()) {
        case GET:
            HttpGet httpGet = new HttpGet(req.buildUri());
            httpGet.setHeaders(commonHeaders);
            return httpGet;
        case POST:
            HttpPost httpPost = new HttpPost(req.buildUri());
            httpPost.setHeaders(commonHeaders);

            if (req.isBodyExists()) {
                httpPost.addHeader(contentTypeHeader);
                httpPost.setEntity(createHttpEntity(req));
            }

            return httpPost;
        case PATCH:
            HttpPatch httpPatch = new HttpPatch(req.buildUri());
            httpPatch.setHeaders(commonHeaders);

            if (req.isBodyExists()) {
                httpPatch.addHeader(contentTypeHeader);
                httpPatch.setEntity(createHttpEntity(req));
            }

            return httpPatch;
        case DELETE:
            HttpDelete httpDelete = new HttpDelete(req.buildUri());
            httpDelete.setHeaders(commonHeaders);

            if (req.isBodyExists()) {
                httpDelete.addHeader(contentTypeHeader);
                httpDelete.setEntity(createHttpEntity(req));
            }

            return httpDelete;
        }
    } catch (URISyntaxException ue) {
        throw new HttpErrorException(ue);
    }

    return null;
}

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private String doPatch(URI uri, StringEntity entity) throws TutumException, RequestUnsuccessfulException {
    HttpPatch patch = new HttpPatch(uri);
    patch.setHeaders(getRequestHeaders());

    if (null != entity) {
        patch.setEntity(entity);/*from w  w w  .  j  a v  a 2 s .  com*/
    }

    return executeHttpRequest(patch);
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

private HttpRequestBase buildRequest(String httpMethod, String requestPath, Object entityContent)
        throws ScalewayApiException {
    LOGGER.debug("Building request for method '{}' and URL '{}'", httpMethod, requestPath);

    HttpRequestBase request = null;//w  w w  .ja va  2 s.  com
    switch (httpMethod) {
    case Constants.HTTP_METHOD_GET:
        request = new HttpGet(requestPath);
        break;
    case Constants.HTTP_METHOD_POST:
        request = new HttpPost(requestPath);
        break;
    case Constants.HTTP_METHOD_DELETE:
        request = new HttpDelete(requestPath);
        break;
    case Constants.HTTP_METHOD_PATCH:
        request = new HttpPatch(requestPath);
        break;
    case Constants.HTTP_METHOD_PUT:
        request = new HttpPut(requestPath);
        break;
    }

    request.setHeader(Constants.HEADER_KEY_AUTH_TOKEN, accessToken);
    request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.HEADER_VALUE_JSON_APPLICATION);

    if (null != entityContent) {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            try {
                StringEntity entity = new StringEntity(serializeObject(entityContent));
                ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
            } catch (UnsupportedEncodingException | JsonProcessingException ex) {
                throw new ScalewayApiException(ex);
            }
        } else {
            LOGGER.error("Attempting to set entity on non applicable base class of '{}'", request.getClass());
        }
    }
    return request;
}

From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java

private String callWSPotch(String token, HttpCon con, String uri, String json)
        throws IOException, ClientProtocolException {

    HttpPatch put = new HttpPatch(uri);

    put.addHeader(new BasicHeader("X-Auth-Token", token));

    StringEntity str = new StringEntity(json, ContentType.APPLICATION_JSON);
    put.setEntity(str);//from w ww  .j  a  va2s. c  o m

    HttpResponse resp = con.getHttp().execute(put);

    json = EntityUtils.toString(resp.getEntity());
    return json;
}

From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java

public RestResponse patchRequest(String requestBody, String param) {
    HttpClient client = new DefaultHttpClient();
    String result = new String();
    RestResponse response = new RestResponse();
    HttpPatch patch = new HttpPatch(DOCSTORE_URL + param);
    try {//  w w  w.jav  a 2s  .c  om
        StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
        patch.setEntity(stringEntity);
        response.setResponse(client.execute(patch));
        result = getEncodeEntityValue(response.getResponse().getEntity());
    } catch (Exception e) {
        logger.error("PATCH response error is ::", e);
    }
    response.setResponseBody(result);
    logger.debug(" PATCH Response Body :: ", response.getResponseBody());
    return response;
}

From source file:com.microsoft.azure.management.trafficmanager.EndpointOperationsImpl.java

/**
* Create or update a Traffic Manager endpoint.
*
* @param resourceGroupName Required. The name of the resource group
* containing the Traffic Manager endpoint to be created or updated.
* @param profileName Required. The name of the Traffic Manager endpoint to
* be created or updated./* w  w  w .j a  v  a 2  s .co m*/
* @param endpointType Required. The type of the Traffic Manager endpoint to
* be created or updated.
* @param endpointName Required. The name of the Traffic Manager endpoint to
* be created or updated.
* @param parameters Required. The Traffic Manager endpoint parameters
* supplied to the Update operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response to a Traffic Manager endpoint 'CreateOrUpdate'
* operation.
*/
@Override
public EndpointUpdateResponse update(String resourceGroupName, String profileName, String endpointType,
        String endpointName, EndpointUpdateParameters parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (profileName == null) {
        throw new NullPointerException("profileName");
    }
    if (endpointType == null) {
        throw new NullPointerException("endpointType");
    }
    if (endpointName == null) {
        throw new NullPointerException("endpointName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndpoint() == null) {
        throw new NullPointerException("parameters.Endpoint");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("profileName", profileName);
        tracingParameters.put("endpointType", endpointType);
        tracingParameters.put("endpointName", endpointName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/trafficmanagerprofiles/";
    url = url + URLEncoder.encode(profileName, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(endpointType, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(endpointName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-11-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPatch httpRequest = new HttpPatch(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode endpointUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = endpointUpdateParametersValue;

    if (parameters.getEndpoint().getId() != null) {
        ((ObjectNode) endpointUpdateParametersValue).put("id", parameters.getEndpoint().getId());
    }

    if (parameters.getEndpoint().getName() != null) {
        ((ObjectNode) endpointUpdateParametersValue).put("name", parameters.getEndpoint().getName());
    }

    if (parameters.getEndpoint().getType() != null) {
        ((ObjectNode) endpointUpdateParametersValue).put("type", parameters.getEndpoint().getType());
    }

    if (parameters.getEndpoint().getProperties() != null) {
        ObjectNode propertiesValue = objectMapper.createObjectNode();
        ((ObjectNode) endpointUpdateParametersValue).put("properties", propertiesValue);

        if (parameters.getEndpoint().getProperties().getTargetResourceId() != null) {
            ((ObjectNode) propertiesValue).put("targetResourceId",
                    parameters.getEndpoint().getProperties().getTargetResourceId());
        }

        if (parameters.getEndpoint().getProperties().getTarget() != null) {
            ((ObjectNode) propertiesValue).put("target", parameters.getEndpoint().getProperties().getTarget());
        }

        if (parameters.getEndpoint().getProperties().getEndpointStatus() != null) {
            ((ObjectNode) propertiesValue).put("endpointStatus",
                    parameters.getEndpoint().getProperties().getEndpointStatus());
        }

        if (parameters.getEndpoint().getProperties().getWeight() != null) {
            ((ObjectNode) propertiesValue).put("weight", parameters.getEndpoint().getProperties().getWeight());
        }

        if (parameters.getEndpoint().getProperties().getPriority() != null) {
            ((ObjectNode) propertiesValue).put("priority",
                    parameters.getEndpoint().getProperties().getPriority());
        }

        if (parameters.getEndpoint().getProperties().getEndpointLocation() != null) {
            ((ObjectNode) propertiesValue).put("endpointLocation",
                    parameters.getEndpoint().getProperties().getEndpointLocation());
        }

        if (parameters.getEndpoint().getProperties().getEndpointMonitorStatus() != null) {
            ((ObjectNode) propertiesValue).put("endpointMonitorStatus",
                    parameters.getEndpoint().getProperties().getEndpointMonitorStatus());
        }

        if (parameters.getEndpoint().getProperties().getMinChildEndpoints() != null) {
            ((ObjectNode) propertiesValue).put("minChildEndpoints",
                    parameters.getEndpoint().getProperties().getMinChildEndpoints());
        }
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        EndpointUpdateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new EndpointUpdateResponse();
        JsonNode responseDoc = null;
        String responseDocContent = IOUtils.toString(responseContent);
        if (responseDocContent == null == false && responseDocContent.length() > 0) {
            responseDoc = objectMapper.readTree(responseDocContent);
        }

        if (responseDoc != null && responseDoc instanceof NullNode == false) {
            Endpoint endpointInstance = new Endpoint();
            result.setEndpoint(endpointInstance);

            JsonNode idValue = responseDoc.get("id");
            if (idValue != null && idValue instanceof NullNode == false) {
                String idInstance;
                idInstance = idValue.getTextValue();
                endpointInstance.setId(idInstance);
            }

            JsonNode nameValue = responseDoc.get("name");
            if (nameValue != null && nameValue instanceof NullNode == false) {
                String nameInstance;
                nameInstance = nameValue.getTextValue();
                endpointInstance.setName(nameInstance);
            }

            JsonNode typeValue = responseDoc.get("type");
            if (typeValue != null && typeValue instanceof NullNode == false) {
                String typeInstance;
                typeInstance = typeValue.getTextValue();
                endpointInstance.setType(typeInstance);
            }

            JsonNode propertiesValue2 = responseDoc.get("properties");
            if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                EndpointProperties propertiesInstance = new EndpointProperties();
                endpointInstance.setProperties(propertiesInstance);

                JsonNode targetResourceIdValue = propertiesValue2.get("targetResourceId");
                if (targetResourceIdValue != null && targetResourceIdValue instanceof NullNode == false) {
                    String targetResourceIdInstance;
                    targetResourceIdInstance = targetResourceIdValue.getTextValue();
                    propertiesInstance.setTargetResourceId(targetResourceIdInstance);
                }

                JsonNode targetValue = propertiesValue2.get("target");
                if (targetValue != null && targetValue instanceof NullNode == false) {
                    String targetInstance;
                    targetInstance = targetValue.getTextValue();
                    propertiesInstance.setTarget(targetInstance);
                }

                JsonNode endpointStatusValue = propertiesValue2.get("endpointStatus");
                if (endpointStatusValue != null && endpointStatusValue instanceof NullNode == false) {
                    String endpointStatusInstance;
                    endpointStatusInstance = endpointStatusValue.getTextValue();
                    propertiesInstance.setEndpointStatus(endpointStatusInstance);
                }

                JsonNode weightValue = propertiesValue2.get("weight");
                if (weightValue != null && weightValue instanceof NullNode == false) {
                    long weightInstance;
                    weightInstance = weightValue.getLongValue();
                    propertiesInstance.setWeight(weightInstance);
                }

                JsonNode priorityValue = propertiesValue2.get("priority");
                if (priorityValue != null && priorityValue instanceof NullNode == false) {
                    long priorityInstance;
                    priorityInstance = priorityValue.getLongValue();
                    propertiesInstance.setPriority(priorityInstance);
                }

                JsonNode endpointLocationValue = propertiesValue2.get("endpointLocation");
                if (endpointLocationValue != null && endpointLocationValue instanceof NullNode == false) {
                    String endpointLocationInstance;
                    endpointLocationInstance = endpointLocationValue.getTextValue();
                    propertiesInstance.setEndpointLocation(endpointLocationInstance);
                }

                JsonNode endpointMonitorStatusValue = propertiesValue2.get("endpointMonitorStatus");
                if (endpointMonitorStatusValue != null
                        && endpointMonitorStatusValue instanceof NullNode == false) {
                    String endpointMonitorStatusInstance;
                    endpointMonitorStatusInstance = endpointMonitorStatusValue.getTextValue();
                    propertiesInstance.setEndpointMonitorStatus(endpointMonitorStatusInstance);
                }

                JsonNode minChildEndpointsValue = propertiesValue2.get("minChildEndpoints");
                if (minChildEndpointsValue != null && minChildEndpointsValue instanceof NullNode == false) {
                    long minChildEndpointsInstance;
                    minChildEndpointsInstance = minChildEndpointsValue.getLongValue();
                    propertiesInstance.setMinChildEndpoints(minChildEndpointsInstance);
                }
            }
        }

        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}