List of usage examples for org.apache.http.client.methods HttpPatch setEntity
public void setEntity(final HttpEntity entity)
From source file:sabina.integration.TestScenario.java
private HttpUriRequest getHttpRequest(String method, String path, String body, boolean secure, String acceptType) {//www. j av a 2 s . c om if (body == null) body = ""; try { String protocol = secure ? "https" : "http"; String uri = protocol + "://localhost:" + port + path; if (method.equals("GET")) { HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Accept", acceptType); return httpGet; } if (method.equals("POST")) { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("Accept", acceptType); httpPost.setEntity(new StringEntity(body)); return httpPost; } if (method.equals("PATCH")) { HttpPatch httpPatch = new HttpPatch(uri); httpPatch.setHeader("Accept", acceptType); httpPatch.setEntity(new StringEntity(body)); return httpPatch; } if (method.equals("DELETE")) { HttpDelete httpDelete = new HttpDelete(uri); httpDelete.setHeader("Accept", acceptType); return httpDelete; } if (method.equals("PUT")) { HttpPut httpPut = new HttpPut(uri); httpPut.setHeader("Accept", acceptType); httpPut.setEntity(new StringEntity(body)); return httpPut; } if (method.equals("HEAD")) return new HttpHead(uri); if (method.equals("TRACE")) return new HttpTrace(uri); if (method.equals("OPTIONS")) return new HttpOptions(uri); throw new IllegalArgumentException("Unknown method " + method); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java
private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri, HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params, InputStream requestEntity) throws Exception { Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity); URL host = RequestContext.getCurrentContext().getRouteHost(); HttpHost httpHost = getHttpHost(host); uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/")); HttpRequest httpRequest;//from w ww. j a v a 2 s.c o m int contentLength = request.getContentLength(); InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength, request.getContentType() != null ? ContentType.create(request.getContentType()) : null); switch (verb.toUpperCase()) { case "POST": HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params)); httpRequest = httpPost; httpPost.setEntity(entity); break; case "PUT": HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params)); httpRequest = httpPut; httpPut.setEntity(entity); break; case "PATCH": HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params)); httpRequest = httpPatch; httpPatch.setEntity(entity); break; default: httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params)); log.debug(uri + this.helper.getQueryString(params)); } try { httpRequest.setHeaders(convertHeaders(headers)); log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName()); CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest); RequestContext.getCurrentContext().set("zuulResponse", zuulResponse); this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(), revertHeaders(zuulResponse.getAllHeaders())); return zuulResponse; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); } }
From source file:org.wso2.am.integration.tests.other.HttpPATCHSupportTestCase.java
@Test(groups = "wso2.am", description = "Check functionality of HTTP PATCH support for APIM") public void testHttpPatchSupport() throws Exception { //Login to the API Publisher apiPublisher.login(user.getUserName(), user.getPassword()); String APIName = "HttpPatchAPI"; String APIContext = "patchTestContext"; String url = getGatewayURLNhttp() + "httpPatchSupportContext"; String providerName = user.getUserName(); String APIVersion = "1.0.0"; APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url)); apiRequest.setVersion(APIVersion);/*ww w . java2s . c om*/ apiRequest.setProvider(providerName); //Adding the API to the publisher apiPublisher.addAPI(apiRequest); //Publish the API APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); apiPublisher.changeAPILifeCycleStatus(updateRequest); String modifiedResource = "{\"paths\":{ \"/*\":{\"patch\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\"," + "\"x-throttling-tier\":\"Unlimited\" },\"get\":{ \"responses\":{\"200\":{}},\"x-auth-type\":\"Application\"," + "\"x-throttling-tier\":\"Unlimited\",\"x-scope\":\"user_scope\"}}},\"swagger\":\"2.0\",\"info\":{\"title\":\"HttpPatchAPI\",\"version\":\"1.0.0\"}," + "\"x-wso2-security\":{\"apim\":{\"x-wso2-scopes\":[{\"name\":\"admin_scope\",\"description\":\"\",\"key\":\"admin_scope\",\"roles\":\"admin\"}," + "{\"name\":\"user_scope\",\"description\":\"\",\"key\":\"user_scope\",\"roles\":\"admin,subscriber\"}]}}}"; //Modify the resources to add the PATCH resource method to the API apiPublisher.updateResourceOfAPI(providerName, APIName, APIVersion, modifiedResource); //Login to the API Store apiStore.login(user.getUserName(), user.getPassword()); //Add an Application in the Store. apiStore.addApplication("HttpPatchSupportAPP", APIMIntegrationConstants.APPLICATION_TIER.LARGE, "", "Test-HTTP-PATCH"); //Subscribe to the new application SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, APIVersion, providerName, "HttpPatchSupportAPP", APIMIntegrationConstants.API_TIER.GOLD); apiStore.subscribe(subscriptionRequest); //Generate a production token and invoke the API APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("HttpPatchSupportAPP"); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject jsonResponse = new JSONObject(responseString); //Get the accessToken generated. String accessToken = jsonResponse.getJSONObject("data").getJSONObject("key").getString("accessToken"); String apiInvocationUrl = getAPIInvocationURLHttp(APIContext, APIVersion); //Invoke the API by sending a PATCH request; HttpClient client = HttpClientBuilder.create().build(); HttpPatch request = new HttpPatch(apiInvocationUrl); request.setHeader("Accept", "application/json"); request.setHeader("Authorization", "Bearer " + accessToken); StringEntity payload = new StringEntity("{\"first\":\"Greg\"}", "UTF-8"); payload.setContentType("application/json"); request.setEntity(payload); HttpResponse httpResponsePatch = client.execute(request); //Assertion assertEquals(httpResponsePatch.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "The response code is not 200 OK"); }
From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java
/** * @param sObject sObject to upsert * @param externalIdField field name of external id field * * @return http status code//from ww w .ja v a 2s . c o m * * @throws IOException on error */ int upsert(SObject sObject, String externalIdField) throws IOException { HttpPatch patch = new HttpPatch(getUri("/sobjects/" + sObject.getType() + "/" + externalIdField + "/" + sObject.getField(externalIdField))); patch.setEntity(getEntityForSObjectFieldsJson(sObject)); patch.addHeader("Content-Type", UPLOAD_CONTENT_TYPE); ProcessedResponse processedResponse = executeRequest(patch); return processedResponse.getHttpResponse().getStatusLine().getStatusCode(); }
From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java
@Override public ServiceInstanceRegistry createInstanceRegistry(final Service service) { init.await();/*from w w w . jav a 2 s . c om*/ LOG.debug("POST: Creating service instance registry"); final HttpPost post = new HttpPost(service.uri()); post.setHeader(HttpHeaders.CONTENT_TYPE, "text/turtle"); post.setEntity(new InputStreamEntity( this.getClass().getResourceAsStream("objects/service-instance-registry.ttl"))); final URI uri; try (CloseableHttpResponse resp = execute(post)) { uri = URI.create(resp.getFirstHeader(HttpHeaders.LOCATION).getValue()); } catch (final Exception e) { throw new RuntimeException("Could not create service instance registry", e); } final HttpPatch patch = new HttpPatch(uri); patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE); patch.setEntity(new StringEntity(String.format("INSERT {?instance <%s> <%s> .} WHERE {?instance a <%s> .}", PROP_IS_SERVICE_INSTANCE_OF, service.uri(), CLASS_SERVICE_INSTANCE), UTF_8)); try (CloseableHttpResponse resp = execute(patch)) { LOG.info("Updating instance registry for {}", service.uri()); } catch (final Exception e) { throw new RuntimeException("Could not update service instance registry", e); } return instancesOf(getService(service.uri())); }
From source file:wercker4j.request.RequestBuilder.java
/** * patch will call token API to update/*from w w w . j a va 2 s .c om*/ * * @param option option to call update token API * @return responseWrapper * @throws Wercker4jException fault statusCode and IO error */ public ResponseWrapper patch(UpdateTokenOption option) throws Wercker4jException { String url = UriTemplate.fromTemplate(endpoint + "/tokens{/tokenId}").set("tokenId", option.tokenId) .expand(); HttpPatch httpPatch = new HttpPatch(url); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); try { httpPatch.setEntity(new StringEntity(mapper.writeValueAsString(option), "UTF-8")); return callPatchAPI(httpPatch); } catch (Exception e) { throw new Wercker4jException(e); } }
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 ww. j av a 2s . c o m * @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:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java
@Override public void register(final URI uri) { init.await();/*from w w w .jav a2 s .co m*/ try { LOG.debug("Registering service {} ", uri); final HttpPatch patch = new HttpPatch(registryContainer); patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE); patch.setEntity(new InputStreamEntity(patchAddService(uri))); try (CloseableHttpResponse resp = execute(patch)) { LOG.info("Adding service {} to registry {}", uri, registryContainer); } } catch (final Exception e) { throw new RuntimeException( String.format("Could not add <%s> to service registry <%s>", uri, registryContainer), e); } update(uri); }
From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java
@Override public ServiceInstanceRegistry instancesOf(final Service service) { init.await();/*from ww w . ja v a 2 s. c o m*/ final URI registryURI = objectResourceOf(service.uri().toString(), PROP_HAS_SERVICE_INSTANCE_REGISTRY, parse(service)); if (registryURI == null) { throw new ResourceNotFoundException("No service instance registry found for service " + service.uri()); } // TODO: Allow this to be pluggable to different service instance registry implementations final Model registry = getRegistry(registryURI, service); return new ServiceInstanceRegistry() { @Override public List<ServiceInstance> instances() { return objectResourcesOf(registryURI.toString(), PROP_HAS_SERVICE_INSTANCE, registry).stream() .map(uri -> new LdpServiceInstanceImpl(uri, service)).collect(Collectors.toList()); } @Override public URI addEndpoint(final URI endpoint) { LOG.debug("PATCH: Adding endpoint <{}> to <{}>", endpoint, registryURI); final HttpPatch patch = new HttpPatch(registryURI); patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE); patch.setEntity( new StringEntity(String.format("INSERT {?instance <%s> <%s> .} WHERE {?instance a <%s> .}", PROP_HAS_ENDPOINT, endpoint, CLASS_SERVICE_INSTANCE), UTF_8)); try (CloseableHttpResponse resp = execute(patch)) { LOG.info("Adding endpoint <{}> to <{}>", endpoint, registryURI); } catch (final Exception e) { throw new RuntimeException( String.format("Failed adding endpoint <%s> to <%s>", endpoint, registryURI), e); } return registryURI; } }; }