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.semagia.cassa.client.GraphClient.java

/**
 * Modifies a graph on the server using a query.
 * //from ww  w.  j  a v  a  2 s .  c o m
 * @param graphURI The graph URI.
 * @param query A query, i.e. SPARQL 1.1 Update.
 * @param mediaType The the content type of the query.
 * @return {@code true} indicating that the graph was updated sucessfully,
 *          otherwise {@code false}.
 * @throws IOException In case of an error.
 */
public boolean modifyGraph(final URI graphURI, final String query, final MediaType mediaType)
        throws IOException {
    final HttpPatch request = new HttpPatch(getGraphURI(graphURI));
    final StringEntity entity = new StringEntity(query);
    // From the spec it's unclear if a media type is required
    // <http://www.w3.org/TR/2012/WD-sparql11-http-rdf-update-20120501/#http-patch>
    // Other methods do not require a media type and the server should guess it/assume a default
    // so we don't mandate a media type here.
    entity.setContentType(mediaType != null ? mediaType.toString() : null);
    request.setEntity(entity);
    final int status = getStatusCode(request);
    return status == 200 || status == 204;
}

From source file:org.onosproject.protocol.http.ctl.HttpSBControllerImpl.java

@Override
public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
    String type = typeOfMediaType(mediaType);

    try {/*w w w . j a v  a 2  s .com*/
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).username() != null) {
            String pwd = deviceMap.get(device).password() == null ? ""
                    : COLON + deviceMap.get(device).password();
            String userPassword = deviceMap.get(device).username() + pwd;
            String base64string = Base64.getEncoder()
                    .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
            httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(type);
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        int responseStatusCode = httpClient.execute(httprequest).getStatusLine().getStatusCode();
        return checkStatusCode(responseStatusCode);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return false;
}

From source file:org.identityconnectors.office365.Office365Connection.java

public boolean patchObject(String path, JSONObject body) {
    log.info("patchRequest(" + path + ")");

    // http://msdn.microsoft.com/en-us/library/windowsazure/dn151671.aspx
    HttpPatch httpPatch = new HttpPatch(getAPIEndPoint(path));
    httpPatch.addHeader("Authorization", this.getToken());
    // patch.addHeader("Content-Type", "application/json;odata=verbose");
    httpPatch.addHeader("DataServiceVersion", "3.0;NetFx");
    httpPatch.addHeader("MaxDataServiceVersion", "3.0;NetFx");
    httpPatch.addHeader("Accept", "application/atom+xml");

    EntityBuilder eb = EntityBuilder.create();
    eb.setText(body.toString());//from w w w.j  a  va2 s.c om
    eb.setContentType(ContentType.create("application/json"));
    httpPatch.setEntity(eb.build());

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {
        HttpResponse response = httpClient.execute(httpPatch);
        HttpEntity entity = response.getEntity();

        if (response.getStatusLine().getStatusCode() != 204) {
            log.error("An error occured when modify an object in Office 365");
            this.invalidateToken();
            StringBuffer sb = new StringBuffer();
            if (entity != null && entity.getContent() != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String s = null;

                log.info("Response :{0}", response.getStatusLine().toString());

                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    log.info(s);
                }
            }
            throw new ConnectorException("Modify Object failed to " + path + " and body of " + body.toString()
                    + ". Error code was " + response.getStatusLine().getStatusCode()
                    + ". Received the following response " + sb.toString());
        } else {
            return true;
        }
    } catch (ClientProtocolException cpe) {
        log.error(cpe, "Error doing patchRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing PATCH to " + path);
    } catch (IOException ioe) {
        log.error(ioe, "IOE Error doing patchRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing PATCH to " + path);
    }
}

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 www .ja  v a 2 s  . 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:net.packet.impl.PacketClient.java

private HttpUriRequest createHttpRequest(Request req) {
    try {/*w  w w .  j a v a 2  s.c om*/
        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 ava  2 s  .  c  om*/

    return executeHttpRequest(patch);
}

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 .j  a  va 2 s. 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.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);

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

    json = EntityUtils.toString(resp.getEntity());
    return json;//from w  w  w.ja v  a 2 s .c  o  m
}