Java Code Examples for org.apache.http.client.methods.HttpPatch#addHeader()

The following examples show how to use org.apache.http.client.methods.HttpPatch#addHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ODataUpdateTests.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void updateProperty(String serviceURI, String resourcePath, String keyPredicate, String property, String value) throws Exception {
    URI httpURI = URI.create(serviceURI + FORWARD_SLASH +
                             resourcePath + OPEN_BRACKET +
                             QUOTE_MARK + keyPredicate + QUOTE_MARK +
                             CLOSE_BRACKET);

    ObjectNode node = OBJECT_MAPPER.createObjectNode();
    node.put(property, value);

    String data = OBJECT_MAPPER.writeValueAsString(node);
    HttpPatch request = new HttpPatch(httpURI);

    StringEntity httpEntity = new StringEntity(data, org.apache.http.entity.ContentType.APPLICATION_JSON);
    httpEntity.setChunked(false);
    request.setEntity(httpEntity);

    Header contentTypeHeader = request.getEntity().getContentType();
    ContentType contentType = ContentType.parse(contentTypeHeader.getValue());

    request.addHeader(HttpHeaders.ACCEPT, "application/json;odata.metadata=full,application/xml,*/*");
    request.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase());
    request.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
    request.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
    request.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString());

    try (CloseableHttpClient client = HttpClients.createMinimal();
        CloseableHttpResponse response = client.execute(request)) {
        StatusLine statusLine = response.getStatusLine();
        assertEquals(HttpStatus.SC_NO_CONTENT, statusLine.getStatusCode());
    }
}
 
Example 2
Source File: RestEndPointMockerTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void willMockAPATCHRequest() throws Exception {

    final MockStep mockPatch = mockSteps.getMocks().get(2);
    String jsonBodyResponse = mockPatch.getResponse().get("body").toString(); // { "id": "cust345", "message": "email updated"  }

    final String bodyJson = mockPatch.getRequest().get("body").toString(); // { "email": "[email protected]" }
    stubFor(patch(urlEqualTo(mockPatch.getUrl()))
            .withRequestBody(equalToJson(bodyJson))
            .willReturn(aResponse()
                    .withStatus(mockPatch.getResponse().get("status").asInt())
                    .withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(jsonBodyResponse)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPatch request = new HttpPatch("http://localhost:9073" + mockPatch.getUrl());
    request.addHeader("Content-Type", "application/json");
    StringEntity entity = new StringEntity(bodyJson);
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);

    final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    System.out.println("### response: \n" + responseBodyActual);

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    JSONAssert.assertEquals(jsonBodyResponse, responseBodyActual, true);

}
 
Example 3
Source File: GitHubPullRequestCreator.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Updates a branch reference to point it at the new commit.
 * @param branchRef
 * @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)
            .toString();
    
    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);
    }
}
 
Example 4
Source File: HttpSBControllerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public int patch(DeviceId device, String request, InputStream payload, MediaType mediaType) {

    try {
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).authentication() == AuthenticationScheme.BASIC) {
            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);
        } else if (deviceMap.get(device).authentication() == AuthenticationScheme.OAUTH2) {
            String token = deviceMap.get(device).token();
            // TODO: support token types other then bearer of OAuth2 authentication
            httprequest.addHeader(AUTHORIZATION_PROPERTY, OAUTH2_BEARER_AUTH_PREFIX + token);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(mediaType.toString());
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        return httpClient.execute(httprequest).getStatusLine().getStatusCode();
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return Status.BAD_REQUEST.getStatusCode();
}
 
Example 5
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void patch(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        String sidpid,
                        Long startdate,
                        Long enddate,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{
    System.out.println("Patch policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling update @ " + resourceLoc);

    PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
    pfpr.setStartDate(startdate);
    if (enddate != null)
        pfpr.setEndDate(enddate);
    pfpr.setVersion(version);
    pfpr.setStatus(status);
    pfpr.setNotes(notes);
    pfpr.setPolicy(policy);

    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(pfpr);

    ContentType mimetype = ContentType.create("application/merge-patch+json");
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch(resourceLoc);
    httpPatch.setEntity(body);
    String requestToHmac = httpPatch.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPatch.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPatch.addHeader("strongkey-content-sha256", contentSHA);
    httpPatch.addHeader("Content-Type", mimetype.getMimeType());
    httpPatch.addHeader("Date", currentDate);
    httpPatch.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpPatch);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during patch fido policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nPatch policy test complete.");
    System.out.println("******************************************");
}
 
Example 6
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void patch(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        String sidpid,
                        Long startdate,
                        Long enddate,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{
    System.out.println("Patch policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling update @ " + resourceLoc);

    PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
    pfpr.setStartDate(startdate);
    if (enddate != null)
        pfpr.setEndDate(enddate);
    pfpr.setVersion(version);
    pfpr.setStatus(status);
    pfpr.setNotes(notes);
    pfpr.setPolicy(policy);

    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(pfpr);

    ContentType mimetype = ContentType.create("application/merge-patch+json");
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch(resourceLoc);
    httpPatch.setEntity(body);
    String requestToHmac = httpPatch.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPatch.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPatch.addHeader("strongkey-content-sha256", contentSHA);
    httpPatch.addHeader("Content-Type", mimetype.getMimeType());
    httpPatch.addHeader("Date", currentDate);
    httpPatch.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpPatch);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during patch fido policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nPatch policy test complete.");
    System.out.println("******************************************");
}
 
Example 7
Source File: BasicHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 2 votes vote down vote up
/**
 * custom header for respective client
 *
 * @param httppatch
 */
public void setHeader(HttpPatch httppatch) {
    httppatch.addHeader("Accept", "application/json");
}