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.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 * Method to create HttpRequest/*from   www  .ja v a2 s.co  m*/
 */

public HttpRequestBase createHttpRequest(String uri, byte[] data, Map<String, String> requestHeaders,
        String requestType) {
    if ("GET".equals(requestType)) {
        HttpGet request = new HttpGet(constructUrl(uri));
        setRequestHeaders(request, requestHeaders);
        return request;
    } else if ("POST".equals(requestType)) {
        HttpPost request = new HttpPost(constructUrl(uri));
        setRequestBody(request, data);
        setRequestHeaders(request, requestHeaders);
        return request;

    } else if ("PUT".equals(requestType)) {
        HttpPut request = new HttpPut(constructUrl(uri));
        setRequestBody(request, data);
        setRequestHeaders(request, requestHeaders);
        return request;

    } else if ("DELETE".equals(requestType)) {
        HttpDelete request = new HttpDelete(constructUrl(uri));
        setRequestBody(request, data);
        setRequestHeaders(request, requestHeaders);
        return request;
    } else if ("PATCH".equals(requestType)) {
        HttpPatch request = new HttpPatch(constructUrl(uri));
        setRequestBody(request, data);
        setRequestHeaders(request, requestHeaders);
        return request;
    } else {
        HttpRequestBase request = null;
        logger.error("Invalid requestType+:" + requestType);
        return request;
    }
}

From source file:com.arangodb.http.HttpManager.java

/**
 * Executes the request// w  ww  .  j  a v a  2  s .co  m
 * 
 * @param requestEntity
 *            the request
 * @return the response of the request
 * @throws ArangoException
 */
private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity requestEntity)
        throws ArangoException, SocketException {

    String url = buildUrl(baseUrl, requestEntity);

    if (logger.isDebugEnabled()) {
        if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
                || requestEntity.type == RequestType.PATCH) {
            logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
        } else {
            logger.debug("[REQ]http-{}: url={}, headers={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers });
        }
    }

    HttpRequestBase request = null;
    switch (requestEntity.type) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        configureBodyParams(requestEntity, post);
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        configureBodyParams(requestEntity, put);
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        configureBodyParams(requestEntity, patch);
        request = patch;
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    }

    // common-header
    String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)";
    request.setHeader("User-Agent", userAgent);

    // optinal-headers
    if (requestEntity.headers != null) {
        for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
            request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
        }
    }

    // Basic Auth
    Credentials credentials = null;
    if (requestEntity.username != null && requestEntity.password != null) {
        credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
    } else if (configure.getUser() != null && configure.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
    }
    if (credentials != null) {
        BasicScheme basicScheme = new BasicScheme();
        try {
            request.addHeader(basicScheme.authenticate(credentials, request, null));
        } catch (AuthenticationException e) {
            throw new ArangoException(e);
        }
    }

    if (this.getHttpMode().equals(HttpMode.ASYNC)) {
        request.addHeader("x-arango-async", "store");
    } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
        request.addHeader("x-arango-async", "true");
    }
    // CURL/httpie Logger
    if (configure.isEnableCURLLogger()) {
        CURLLogger.log(url, requestEntity, userAgent, credentials);
    }
    HttpResponse response = null;
    if (preDefinedResponse != null) {
        return preDefinedResponse;
    }
    try {
        response = client.execute(request);
        if (response == null) {
            return null;
        }

        HttpResponseEntity responseEntity = new HttpResponseEntity();

        // http status
        StatusLine status = response.getStatusLine();
        responseEntity.statusCode = status.getStatusCode();
        responseEntity.statusPhrase = status.getReasonPhrase();

        logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);

        // ??
        // // TODO etag???
        Header etagHeader = response.getLastHeader("etag");
        if (etagHeader != null) {
            responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
        }
        // Map???
        responseEntity.headers = new TreeMap<String, String>();
        for (Header header : response.getAllHeaders()) {
            responseEntity.headers.put(header.getName(), header.getValue());
        }

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if (contentType != null) {
                responseEntity.contentType = contentType.getValue();
                if (responseEntity.isDumpResponse()) {
                    responseEntity.stream = entity.getContent();
                    logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
                }
            }
            // Close stream in this method.
            if (responseEntity.stream == null) {
                responseEntity.text = IOUtils.toString(entity.getContent());
                logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
            }
        }

        if (this.getHttpMode().equals(HttpMode.ASYNC)) {
            Map<String, String> map = responseEntity.getHeaders();
            this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject());
        } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
            return null;
        }

        return responseEntity;
    } catch (SocketException ex) {
        throw ex;
    } catch (ClientProtocolException e) {
        throw new ArangoException(e);
    } catch (IOException e) {
        throw new ArangoException(e);
    }
}

From source file:com.buffalokiwi.api.API.java

/**
 * A factory method for creating a new request and adding headers 
 * @param type Type of request/*from  w ww.  ja v a  2s  .c om*/
 * @param url URL 
 * @param headers Some headers
 * @return the request 
 * @throws APIException  
 */
private HttpUriRequest createRequest(HttpMethod type, final String url, final Map<String, String> headers)
        throws APIException {
    switch (type) {
    case GET:
        //..Prepare the request
        final HttpGet get = new HttpGet(stringToURI(url));

        //..Add any extra headers
        addHeaders(get, headers);

        return get;

    case POST:
        //..Create the post request
        final HttpPost post = new HttpPost(stringToURI(url));

        //..Add any additional headers
        addHeaders(post, headers);
        return post;

    case PUT:
        final HttpPut put = new HttpPut(stringToURI(url));

        //..Add any extra headers
        addHeaders(put, headers);
        return put;

    case PATCH:
        final HttpPatch patch = new HttpPatch(stringToURI(url));

        addHeaders(patch, headers);
        return patch;

    case DELETE:
        final HttpDelete del = new HttpDelete(stringToURI(url));
        addHeaders(del, headers);
        return del;

    default:
        throw new NotImplementedException("not implemented yet");
    }
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

/**
 * Executes request command//from ww  w  .  java 2s.  c  o m
 *
 * @param command REST request representation
 * @return Future wrapper of REST response
 * @throws RestEndpointIOException In case of error
 * @see com.github.avarabyeu.wills.Will
 */
@Override
public final <RQ, RS> Will<Response<RS>> executeRequest(RestCommand<RQ, RS> command)
        throws RestEndpointIOException {
    URI uri = spliceUrl(command.getUri());
    HttpUriRequest rq;
    Serializer serializer;
    switch (command.getHttpMethod()) {
    case GET:
        rq = new HttpGet(uri);
        break;
    case POST:
        serializer = getSupportedSerializer(command.getRequest());
        rq = new HttpPost(uri);
        ((HttpPost) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()),
                ContentType.create(serializer.getMimeType())));
        break;
    case PUT:
        serializer = getSupportedSerializer(command.getRequest());
        rq = new HttpPut(uri);
        ((HttpPut) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()),
                ContentType.create(serializer.getMimeType())));
        break;
    case DELETE:
        rq = new HttpDelete(uri);
        break;
    case PATCH:
        serializer = getSupportedSerializer(command.getRequest());
        rq = new HttpPatch(uri);
        ((HttpPatch) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()),
                ContentType.create(serializer.getMimeType())));
        break;
    default:
        throw new IllegalArgumentException("Method '" + command.getHttpMethod() + "' is unsupported");
    }

    return executeInternal(rq, new TypeConverterCallback<RS>(serializers, command.getResponseType()));
}

From source file:org.coding.git.api.CodingNetConnection.java

@NotNull
private CloseableHttpResponse doREST(@NotNull final String uri, @Nullable final String requestBody,
        @NotNull final Collection<Header> headers, @NotNull final HttpVerb verb) throws IOException {
    HttpRequestBase request;//from   w  w w .  ja v  a2  s  .com
    switch (verb) {
    case POST:
        request = new HttpPost(uri);
        if (requestBody != null) {
            ((HttpPost) request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        }
        break;
    case PATCH:
        request = new HttpPatch(uri);
        if (requestBody != null) {
            ((HttpPatch) request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        }
        break;
    case GET:
        request = new HttpGet(uri);
        break;
    case DELETE:
        request = new HttpDelete(uri);
        break;
    case HEAD:
        request = new HttpHead(uri);
        break;
    default:
        throw new IllegalStateException("Unknown HttpVerb: " + verb.toString());
    }

    for (Header header : headers) {
        request.addHeader(header);
    }

    myRequest = request;
    return myClient.execute(request);
}

From source file:io.apicurio.hub.api.github.GitHubPullRequestCreator.java

/**
 * Updates a branch reference to point it at the new commit.
 * @param branchRef//from w  w w  . j  a  va  2s .  c om
 * @param commit
 */
private GitHubBranchReference updateBranchRef(GitHubBranchReference branchRef, GitHubCommit commit)
        throws GitHubException {
    String bref = branchRef.getRef();
    if (bref.startsWith("refs/")) {
        bref = bref.substring(5);
    }
    String url = this.endpoint("/repos/:owner/:repo/git/refs/:ref").bind("owner", this.organization)
            .bind("repo", this.repository).bind("ref", bref).url();

    GitHubUpdateReference requestBody = new GitHubUpdateReference();
    requestBody.setSha(commit.getSha());

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPatch request = new HttpPatch(url);
        request.setEntity(new StringEntity(mapper.writeValueAsString(requestBody)));
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Accept", "application/json");
        addSecurityTo(request);

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Invalid response code: " + response.getStatusLine().getStatusCode()
                        + " :: " + response.getStatusLine().getReasonPhrase());
            }
            try (InputStream contentStream = response.getEntity().getContent()) {
                GitHubBranchReference ref = mapper.readValue(contentStream, GitHubBranchReference.class);
                ref.setName(branchRef.getName());
                return ref;
            }
        }
    } catch (IOException e) {
        throw new GitHubException("Error creating a GH commit.", e);
    }
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * PATCH request with payload to a server
 * HTTP or HTTPS shall already be initialized
 * using either the initHttp or initHttps methods.
 * @param payLoad/*from  w  w  w . ja va2s.co  m*/
 *        String to be sent in the HTTP request payload
 * @return CoreResponse
 */
public CoreResponse patch(String payLoad) {
    final String METHOD_NAME = "patch(String): ";

    try (CloseableHttpClient client = getClient();) {
        // Instantiate a PATCH Request and define the Target URL
        HttpPatch httpPatch = new HttpPatch(this.targetURL);
        // Build the HTTP request header from the HeadersMap
        addHeader(httpPatch);
        // Build the HTTP request message content
        StringEntity entity = new StringEntity(payLoad);
        httpPatch.setEntity(entity);

        return executeRequest(client, httpPatch);

    } catch (IOException exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + "Exception: " + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }
}

From source file:org.dasein.cloud.google.GoogleMethod.java

public @Nullable JSONObject patch(@Nonnull String service, @Nonnull JSONObject jsonPayload)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + Google.class.getName() + ".patch(" + service + ")");
    }// w  ww  .  jav a2  s. c om
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [PATCH (" + (new Date()) + ")] -> " + service
                + " >--------------------------------------------------------------------------------------");
    }
    try {
        ProviderContext ctx = provider.getContext();

        if (ctx == null) {
            throw new CloudException("No context was set for this request");
        }

        String endpoint = getEndpoint(ctx, service);

        if (logger.isDebugEnabled()) {
            logger.debug("endpoint=" + endpoint);
            logger.debug("");
            logger.debug("Getting accessToken from cache");
        }

        Cache<String> cache = Cache.getInstance(provider, "accessToken", String.class, CacheLevel.CLOUD,
                new TimePeriod<Hour>(1, TimePeriod.HOUR));
        Collection<String> accessToken = (Collection<String>) cache.get(ctx);

        if (accessToken == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Getting the accessToken afresh");
            }
            accessToken = new ArrayList<String>();
            accessToken.add(getAccessToken(ctx));
            cache.put(ctx, accessToken);
        }

        //TODO: Logging access token is not good
        if (logger.isDebugEnabled()) {
            logger.debug("accessToken=" + accessToken);
        }

        String paramString = "?access_token=" + accessToken.iterator().next()
                + "&token_type=Bearer&expires_in=3600";

        if (logger.isDebugEnabled()) {
            logger.debug("Param string=" + paramString);
        }
        HttpPatch patch = new HttpPatch(endpoint + paramString);
        HttpClient client = getClient(ctx, endpoint.startsWith("https"));

        StringEntity stringEntity;
        try {
            stringEntity = new StringEntity(jsonPayload.toString());
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            return null;
        }
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        patch.setEntity(stringEntity);

        if (wire.isDebugEnabled()) {
            wire.debug(patch.getRequestLine().toString());
            for (Header header : patch.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(patch);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
            }
        } catch (IOException e) {
            logger.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int status = response.getStatusLine().getStatusCode();

        if (status == NOT_FOUND) {
            return null;
        }
        if (status == OK || status == ACCEPTED) {
            HttpEntity entity = response.getEntity();
            String json;

            if (entity == null) {
                return null;
            }
            try {
                json = EntityUtils.toString(entity);
                if (wire.isDebugEnabled()) {
                    wire.debug(json);
                }
            } catch (IOException e) {
                logger.error("Failed to read JSON entity");
                e.printStackTrace();
                throw new CloudException(e);
            }
            try {
                return new JSONObject(json);
            } catch (JSONException e) {
                logger.error("Invalid JSON from cloud: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
        } else if (status == NOT_FOUND) {
            return null;
        } else if (status == 400 && service.endsWith("patch")) {
            return null;
        }
        throw new GoogleException(new GoogleException.ParsedException(response));
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + GoogleMethod.class.getName() + ".patch()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [PATCH (" + (new Date()) + ")] -> " + service
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}