org.apache.http.client.methods.HttpPatch Java Examples

The following examples show how to use org.apache.http.client.methods.HttpPatch. 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: ODataTestUtils.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
public static int sendPATCH(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPatch httpPatch = new HttpPatch(endpoint);
    for (String headerType : headers.keySet()) {
        httpPatch.setHeader(headerType, headers.get(headerType));
    }
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPatch.setHeader("Content-Type", "application/json");
        }
        httpPatch.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPatch);
    return httpResponse.getStatusLine().getStatusCode();
}
 
Example #2
Source File: ApacheHttpRequestFactory.java    From aws-sdk-java-v2 with Apache License 2.0 7 votes vote down vote up
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, String uri) {
    switch (request.httpRequest().method()) {
        case HEAD:
            return new HttpHead(uri);
        case GET:
            return new HttpGet(uri);
        case DELETE:
            return new HttpDelete(uri);
        case OPTIONS:
            return new HttpOptions(uri);
        case PATCH:
            return wrapEntity(request, new HttpPatch(uri));
        case POST:
            return wrapEntity(request, new HttpPost(uri));
        case PUT:
            return wrapEntity(request, new HttpPut(uri));
        default:
            throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
    }
}
 
Example #3
Source File: HttpComponentsClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
	switch (httpMethod) {
		case GET:
			return new HttpGet(uri);
		case HEAD:
			return new HttpHead(uri);
		case POST:
			return new HttpPost(uri);
		case PUT:
			return new HttpPut(uri);
		case PATCH:
			return new HttpPatch(uri);
		case DELETE:
			return new HttpDelete(uri);
		case OPTIONS:
			return new HttpOptions(uri);
		case TRACE:
			return new HttpTrace(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
	}
}
 
Example #4
Source File: HttpComponentsClientHttpRequestFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
	switch (httpMethod) {
		case GET:
			return new HttpGet(uri);
		case HEAD:
			return new HttpHead(uri);
		case POST:
			return new HttpPost(uri);
		case PUT:
			return new HttpPut(uri);
		case PATCH:
			return new HttpPatch(uri);
		case DELETE:
			return new HttpDelete(uri);
		case OPTIONS:
			return new HttpOptions(uri);
		case TRACE:
			return new HttpTrace(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
	}
}
 
Example #5
Source File: HttpComponentsClientHttpRequestFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
	switch (httpMethod) {
		case GET:
			return new HttpGet(uri);
		case HEAD:
			return new HttpHead(uri);
		case POST:
			return new HttpPost(uri);
		case PUT:
			return new HttpPut(uri);
		case PATCH:
			return new HttpPatch(uri);
		case DELETE:
			return new HttpDelete(uri);
		case OPTIONS:
			return new HttpOptions(uri);
		case TRACE:
			return new HttpTrace(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
	}
}
 
Example #6
Source File: BrocadeVcsApiTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssociateMacToNetwork() throws BrocadeVcsApiException, IOException {
    // Prepare

    method = mock(HttpPatch.class);

    response = mock(HttpResponse.class);
    final StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
    when(response.getStatusLine()).thenReturn(statusLine);

    // Execute
    api.associateMacToNetwork(NETWORK_ID, MAC_ADDRESS_32);

    // Assert
    verify(method, times(1)).releaseConnection();
    assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
    assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
}
 
Example #7
Source File: BrocadeVcsApiTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisassociateMacFromNetwork() throws BrocadeVcsApiException, IOException {
    // Prepare

    method = mock(HttpPatch.class);

    response = mock(HttpResponse.class);
    final StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
    when(response.getStatusLine()).thenReturn(statusLine);

    // Execute
    api.disassociateMacFromNetwork(NETWORK_ID, MAC_ADDRESS_32);

    // Assert
    verify(method, times(1)).releaseConnection();
    assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
    assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
}
 
Example #8
Source File: BrocadeVcsApiTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateNetwork() throws BrocadeVcsApiException, IOException {
    // Prepare

    method = mock(HttpPatch.class);

    response = mock(HttpResponse.class);
    final StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
    when(response.getStatusLine()).thenReturn(statusLine);

    // Execute
    api.createNetwork(VLAN_ID, NETWORK_ID);

    // Assert
    verify(method, times(6)).releaseConnection();
    assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
    assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
}
 
Example #9
Source File: BrocadeVcsApiTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteNetwork() throws BrocadeVcsApiException, IOException {
    // Prepare

    method = mock(HttpPatch.class);

    response = mock(HttpResponse.class);
    final StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
    when(response.getStatusLine()).thenReturn(statusLine);

    // Execute
    api.deleteNetwork(VLAN_ID, NETWORK_ID);

    // Assert
    verify(method, times(3)).releaseConnection();
    assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
    assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
}
 
Example #10
Source File: BrocadeVcsApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException {
    String url;
    try {
        url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString();
    } catch (final MalformedURLException e) {
        s_logger.error("Unable to build Brocade Switch API URL", e);
        throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new HttpPost(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new HttpGet(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new HttpDelete(url);
    } else if ("patch".equalsIgnoreCase(type)) {
        return new HttpPatch(url);
    } else {
        throw new BrocadeVcsApiException("Requesting unknown method type");
    }
}
 
Example #11
Source File: TripPinServiceTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateEntity() throws Exception {
  String payload = "{" + 
      "  \"Emails\":[" + 
      "     \"[email protected]\"," +
      "     \"[email protected]\"" +        
      "         ]" + 
      "}";
  HttpPatch updateRequest = new HttpPatch(baseURL+"/People('kristakemp')");
  updateRequest.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
  httpSend(updateRequest, 204);
  
  HttpResponse response = httpGET(baseURL + "/People('kristakemp')", 200);
  JsonNode node = getJSONNode(response);
  assertEquals(baseURL+"/$metadata#People/$entity", node.get("@odata.context").asText());
  assertEquals("[email protected]", node.get("Emails").get(0).asText());
  assertEquals("[email protected]", node.get("Emails").get(1).asText());
}
 
Example #12
Source File: ServerFrontendITest.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@Test
@Category({
	ExceptionPath.class
})
@OperateOnDeployment(DEPLOYMENT)
public void testNoPatchSupport(@ArquillianResource final URL url) throws Exception {
	LOGGER.info("Started {}",testName.getMethodName());
	HELPER.base(url);
	HELPER.setLegacy(false);

	HttpPatch patch = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH,HttpPatch.class);
	patch.setEntity(
		new StringEntity(
			TEST_SUITE_BODY,
			ContentType.create("text/turtle", "UTF-8"))
	);
	Metadata patchResponse=HELPER.httpRequest(patch);
	assertThat(patchResponse.status,equalTo(HttpStatus.SC_METHOD_NOT_ALLOWED));
	assertThat(patchResponse.body,notNullValue());
	assertThat(patchResponse.contentType,startsWith("text/plain"));
	assertThat(patchResponse.language,equalTo(Locale.ENGLISH));
}
 
Example #13
Source File: ApacheHttpRequestFactory.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private HttpRequestBase createApacheRequest(Request<?> request, String uri, String encodedParams) throws FakeIOException {
    switch (request.getHttpMethod()) {
        case HEAD:
            return new HttpHead(uri);
        case GET:
            return new HttpGet(uri);
        case DELETE:
            return new HttpDelete(uri);
        case OPTIONS:
            return new HttpOptions(uri);
        case PATCH:
            return wrapEntity(request, new HttpPatch(uri), encodedParams);
        case POST:
            return wrapEntity(request, new HttpPost(uri), encodedParams);
        case PUT:
            return wrapEntity(request, new HttpPut(uri), encodedParams);
        default:
            throw new SdkClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }
}
 
Example #14
Source File: cfHttpConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private HttpUriRequest resolveMethod( String _method, boolean _multipart ) throws cfmRunTimeException {
	String method = _method.toUpperCase();
	if ( method.equals( "GET" ) ) {
		return new HttpGet();
	} else if ( method.equals( "POST" ) ) {
		return new HttpPost();
	} else if ( method.equals( "HEAD" ) ) {
		return new HttpHead();
	} else if ( method.equals( "TRACE" ) ) {
		return new HttpTrace();
	} else if ( method.equals( "DELETE" ) ) {
		return new HttpDelete();
	} else if ( method.equals( "OPTIONS" ) ) {
		return new HttpOptions();
	} else if ( method.equals( "PUT" ) ) {
		return new HttpPut();
	} else if ( method.equals( "PATCH" ) ) {
		return new HttpPatch();
	}
	throw newRunTimeException( "Unsupported METHOD value [" + method + "]. Valid METHOD values are GET, POST, HEAD, TRACE, DELETE, OPTIONS, PATCH and PUT." );
}
 
Example #15
Source File: BulkV2Connection.java    From components with Apache License 2.0 6 votes vote down vote up
public JobInfoV2 updateJob(String jobId, JobStateEnum state) throws BulkV2ClientException {
    String endpoint = getRestEndpoint();
    endpoint += "jobs/ingest/" + jobId;
    UpdateJobRequest request = new UpdateJobRequest.Builder(state).build();
    try {
        HttpPatch httpPatch = (HttpPatch) createRequest(endpoint, HttpMethod.PATCH);
        StringEntity entity = new StringEntity(serializeToJson(request), ContentType.APPLICATION_JSON);

        httpPatch.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPatch);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new BulkV2ClientException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            return deserializeJsonToObject(responseEntity.getContent(), JobInfoV2.class);
        } else {
            throw new IOException(MESSAGES.getMessage("error.job.info"));
        }
    } catch (BulkV2ClientException bec) {
        throw bec;
    } catch (IOException e) {
        throw new BulkV2ClientException(MESSAGES.getMessage("error.query.job"), e);
    }
}
 
Example #16
Source File: HttpComponentsClientHttpRequestFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
	switch (httpMethod) {
		case GET:
			return new HttpGet(uri);
		case HEAD:
			return new HttpHead(uri);
		case POST:
			return new HttpPost(uri);
		case PUT:
			return new HttpPut(uri);
		case PATCH:
			return new HttpPatch(uri);
		case DELETE:
			return new HttpDelete(uri);
		case OPTIONS:
			return new HttpOptions(uri);
		case TRACE:
			return new HttpTrace(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
	}
}
 
Example #17
Source File: ODataTestUtils.java    From product-ei with Apache License 2.0 6 votes vote down vote up
public static int sendPATCH(String endpoint, String content, Map<String, String> headers) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPatch httpPatch = new HttpPatch(endpoint);
	for (String headerType : headers.keySet()) {
		httpPatch.setHeader(headerType, headers.get(headerType));
	}
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		if (headers.get("Content-Type") == null) {
			httpPatch.setHeader("Content-Type", "application/json");
		}
		httpPatch.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPatch);
	return httpResponse.getStatusLine().getStatusCode();
}
 
Example #18
Source File: ClientImpl.java    From datamill with ISC License 6 votes vote down vote up
protected HttpUriRequest buildHttpRequest(Method method, URI uri) {
    switch (method) {
        case OPTIONS:
            return new HttpOptions(uri);
        case GET:
            return new HttpGet(uri);
        case HEAD:
            return new HttpHead(uri);
        case POST:
            return new HttpPost(uri);
        case PUT:
            return new HttpPut(uri);
        case DELETE:
            return new HttpDelete(uri);
        case TRACE:
            return new HttpTrace(uri);
        case PATCH:
            return new HttpPatch(uri);
        default:
            throw new IllegalArgumentException("Method " + method + " is not implemented!");
    }
}
 
Example #19
Source File: HttpComponentsRequestFactory.java    From fahrschein with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param method the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
private static HttpUriRequest createHttpUriRequest(String method, URI uri) {
    switch (method) {
        case "GET":
            return new HttpGet(uri);
        case "HEAD":
            return new HttpHead(uri);
        case "POST":
            return new HttpPost(uri);
        case "PUT":
            return new HttpPut(uri);
        case "PATCH":
            return new HttpPatch(uri);
        case "DELETE":
            return new HttpDelete(uri);
        case "OPTIONS":
            return new HttpOptions(uri);
        case "TRACE":
            return new HttpTrace(uri);
        default:
            throw new IllegalArgumentException("Invalid HTTP method: " + method);
    }
}
 
Example #20
Source File: JDiscHttpServletTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void requireThatServerRespondsToAllMethods() throws Exception {
    final TestDriver driver = TestDrivers.newInstance(newEchoHandler());
    final URI uri = driver.client().newUri("/status.html");
    driver.client().execute(new HttpGet(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpPost(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpHead(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpPut(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpDelete(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpOptions(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpTrace(uri))
          .expectStatusCode(is(OK));
    driver.client().execute(new HttpPatch(uri))
            .expectStatusCode(is(OK));
    assertThat(driver.close(), is(true));
}
 
Example #21
Source File: BasicHttpTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void patch() throws Exception {
  HttpPatch get = new HttpPatch(URI.create(getEndpoint().toString() + "aaa/bbb/ccc"));
  final HttpResponse response = getHttpClient().execute(get);

  assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());
  final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
  assertTrue(payload.contains("error"));
}
 
Example #22
Source File: ApacheHttpRequest.java    From junit-servers with MIT License 5 votes vote down vote up
HttpRequestBase create(HttpMethod httpMethod) {
	if (httpMethod == HttpMethod.GET) {
		return new HttpGet();
	}

	if (httpMethod == HttpMethod.POST) {
		return new HttpPost();
	}

	if (httpMethod == HttpMethod.PUT) {
		return new HttpPut();
	}

	if (httpMethod == HttpMethod.DELETE) {
		return new HttpDelete();
	}

	if (httpMethod == HttpMethod.PATCH) {
		return new HttpPatch();
	}

	if (httpMethod == HttpMethod.HEAD) {
		return new HttpHead();
	}

	throw new UnsupportedOperationException("Method " + httpMethod + " is not supported by apache http-client");
}
 
Example #23
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @param url URL of service
 * @param response response pre-populated with request to send. Response content and
 *          statusCode will be filled.
 * @param headers http headers to add
 * @param type contentType for request.
 */
public void patch(String url, HttpResponse response, Map<String, Object> headers, String type){
    HttpPatch methodPatch = new HttpPatch(url);
    ContentType contentType = ContentType.parse(type);
    HttpEntity ent = new StringEntity(response.getRequest(), contentType);
    methodPatch.setEntity(ent);
    getResponse(url,response,methodPatch, headers);
}
 
Example #24
Source File: BrocadeVcsApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected <T> boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException {

        final boolean result = true;

        if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {
            throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
        }

        final HttpPatch pm = (HttpPatch)createMethod("patch", uri);
        pm.setHeader("Accept", "application/vnd.configuration.resource+xml");

        pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML));

        final HttpResponse response = executeMethod(pm);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {

            String errorMessage;
            try {
                errorMessage = responseToErrorMessage(response);
            } catch (final IOException e) {
                s_logger.error("Failed to update object : " + e.getMessage());
                throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage());
            }

            pm.releaseConnection();
            s_logger.error("Failed to update object : " + errorMessage);
            throw new BrocadeVcsApiException("Failed to update object : " + errorMessage);
        }

        pm.releaseConnection();

        return result;
    }
 
Example #25
Source File: CustomRedirectStrategy.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpUriRequest getRedirect(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = null;
    try {
        uri = getLocationURI(request, response, context);
    } catch (URISyntaxException ex) {
        Logger.getLogger(CustomRedirectStrategy.class.getName()).log(Level.SEVERE, null, ex);
    }
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                return copyEntity(new HttpPost(uri), request);
            } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
                return copyEntity(new HttpPut(uri), request);
            } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
                return new HttpDelete(uri);
            } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
                return new HttpTrace(uri);
            } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
                return new HttpOptions(uri);
            } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
                return copyEntity(new HttpPatch(uri), request);
            }
        }
        return new HttpGet(uri);
    }
}
 
Example #26
Source File: DigitalOceanClient.java    From digitalocean-api-java with MIT License 5 votes vote down vote up
private String doPatch(URI uri, HttpEntity entity)
    throws DigitalOceanException, RequestUnsuccessfulException {
  HttpPatch patch = new HttpPatch(uri);
  patch.setHeaders(requestHeaders);

  if (null != entity) {
    patch.setEntity(entity);
  }

  return executeHttpRequest(patch);
}
 
Example #27
Source File: CsrfProtectionITBase.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void patchBlockedHasJsonResponse() throws Exception{
    HttpUriRequest request = new HttpPatch(defaultURI());

    response = client.execute(request);
    assertEquals("status", HttpStatus.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
    assertThat("reason", response.getStatusLine().getReasonPhrase(), containsString("Referer"));
    assertThat("body", EntityUtils.toString(response.getEntity()), containsString("Referer"));
}
 
Example #28
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 #29
Source File: AbstractRefTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
protected HttpResponse callUri(
    final ODataHttpMethod httpMethod, final String uri,
    final String additionalHeader, final String additionalHeaderValue,
    final String requestBody, final String requestContentType,
    final HttpStatusCodes expectedStatusCode) throws Exception {

  HttpRequestBase request =
      httpMethod == ODataHttpMethod.GET ? new HttpGet() :
          httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() :
              httpMethod == ODataHttpMethod.POST ? new HttpPost() :
                  httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
  request.setURI(URI.create(getEndpoint() + uri));
  if (additionalHeader != null) {
    request.addHeader(additionalHeader, additionalHeaderValue);
  }
  if (requestBody != null) {
    ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
    request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
  }

  final HttpResponse response = getHttpClient().execute(request);

  assertNotNull(response);
  assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

  if (expectedStatusCode == HttpStatusCodes.OK) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
  } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
    assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
  } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
    assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
  }

  return response;
}
 
Example #30
Source File: RequestContentTypeTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unsupportedContentTypeParameter() throws Exception {
  HttpPatch patch = new HttpPatch(URI.create(getEndpoint().toString() + "Rooms('1')"));
  patch.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.APPLICATION_JSON + ";illegal=wrong");
  final HttpResponse response = getHttpClient().execute(patch);
  assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatusLine().getStatusCode());
}