List of usage examples for org.apache.http.client.methods HttpPut setEntity
public void setEntity(final HttpEntity entity)
From source file:org.fcrepo.camel.FedoraClient.java
/** * Make a PUT request// w w w.j a v a2 s. com */ public FedoraResponse put(final URI url, final String body, final String contentType) throws ClientProtocolException, IOException, HttpOperationFailedException { final HttpPut request = new HttpPut(url); if (contentType != null) { request.addHeader("Content-Type", contentType); } if (body != null) { request.setEntity(new StringEntity(body)); } final HttpResponse response = httpclient.execute(request); final int status = response.getStatusLine().getStatusCode(); final String contentTypeHeader = getContentTypeHeader(response); if ((status >= 200 && status < 300) || !this.throwExceptionOnFailure) { final HttpEntity entity = response.getEntity(); return new FedoraResponse(url, status, contentTypeHeader, null, entity != null ? EntityUtils.toString(entity) : null); } else { throw buildHttpOperationFailedException(url, response); } }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
@Override public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = getRequest(method, url); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); for (String name : headersToOverwrite.keySet()) { request.setHeader(name, headersToOverwrite.get(name)); }/*from w w w . j a va 2 s . c om*/ String oAuthNonce = String.valueOf(new SecureRandom().nextLong()); Long oAuthTimestamp = System.currentTimeMillis() / 1000; String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp); String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp); request.setHeader("Authorization", authorizationHeader); if (method == HttpMethod.POST) { HttpPost postRequest = (HttpPost) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); postRequest.setEntity(entity); } else if (method == HttpMethod.PUT) { HttpPut putRequest = (HttpPut) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); putRequest.setEntity(entity); } org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request); if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) { HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset); throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse); } return toReturnValue(apacheHCResponse, charset); }
From source file:com.vsct.dt.hesperides.indexation.ElasticSearchIndexationExecutor.java
public void reset() throws IOException { /* Reset the index */ HttpDelete deleteIndex = null;/*from w w w . java2s .c om*/ try { deleteIndex = new HttpDelete("/" + elasticSearchClient.getIndex()); elasticSearchClient.getClient().execute(elasticSearchClient.getHost(), deleteIndex); } catch (final Exception e) { LOGGER.info( "Could not delete elastic search index. This mostly happens when there is no index already"); } finally { if (deleteIndex != null) { deleteIndex.releaseConnection(); } } LOGGER.debug("Deleted Hesperides index {}", elasticSearchClient.getIndex()); /* Add global mapping */ HttpPut putGlobalMapping = null; try (InputStream globalMappingFile = this.getClass().getClassLoader() .getResourceAsStream("elasticsearch/global_mapping.json")) { putGlobalMapping = new HttpPut("/" + elasticSearchClient.getIndex()); putGlobalMapping.setEntity(new InputStreamEntity(globalMappingFile)); elasticSearchClient.getClient().execute(elasticSearchClient.getHost(), putGlobalMapping); LOGGER.debug("Put new global mapping in {}", elasticSearchClient.getIndex()); } finally { if (putGlobalMapping != null) { putGlobalMapping.releaseConnection(); } } /* Add documents mapping */ for (final Mapping mapping : MAPPINGS) { HttpPut putMapping = null; try (InputStream mappingFile = this.getClass().getClassLoader().getResourceAsStream(mapping.resource)) { putMapping = new HttpPut( "/" + elasticSearchClient.getIndex() + "/" + mapping.documentName + "/_mapping"); putMapping.setEntity(new InputStreamEntity(mappingFile)); elasticSearchClient.getClient().execute(elasticSearchClient.getHost(), putMapping); LOGGER.debug("Put new mapping in {}", mapping.documentName); } finally { if (putMapping != null) { putMapping.releaseConnection(); } } } }
From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.crud.OpenAMCrudConnector.java
/** * @param group/* w w w. j a v a2 s .c o m*/ * @return {@link IOpenAMGroupResponse} * @throws Exception */ @Override public IOpenAMGroupResponse updateGroupAddingUser(IOpenAMGroup group) throws Exception { Preconditions.checkNotNull(group, "The group must not be null"); logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO UPDATE GROUP : {} adding USER WITH " + "OPENAM_CONNECTOR_SETTINGS : {} \n", group, this.openAMConnectorSettings); OpenAMUpdateGroupAddUserRequest updateGroupAddUserRequest = this.openAMRequestMediator .getRequest(UPDATE_GROUP_ADD_USER); URI uri = this.buildURI(this.openAMConnectorSettings, updateGroupAddUserRequest.setExtraPathParam(group.getGroupName())).build(); logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_UPDATE_GROUP_ADDING_USER_CONNECTOR_URI : {}\n", URLDecoder.decode(uri.toString(), "UTF-8")); logger.debug(":::::::::::::::::::::::::::::::UPDATE_GROUP_REQUEST_AS_STRING : {}\n", this.openAMReader.writeValueAsString(group)); IOpenAMAuthenticate openAMAuthenticate = super.authenticate(); logger.debug("::::::::::::::::::::::::::::::AUTHENTICATE_FOR_UPDATE_GROUP : {}\n", openAMAuthenticate); HttpPut httpPut = new HttpPut(uri); httpPut.addHeader("Content-Type", "application/json"); httpPut.addHeader(this.openAMCookieInfo.getOpenAMCookie(), openAMAuthenticate.getTokenId()); httpPut.setEntity( new StringEntity(this.openAMReader.writeValueAsString(group), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = this.httpClient.execute(httpPut); if (response.getStatusLine().getStatusCode() != 200) { IOpenAMErrorResponse openAMErrorResponse = this.openAMReader .readValue(response.getEntity().getContent(), OpenAMErrorResponse.class); throw new IllegalStateException( "OpenAMUpdateUser Error Code : " + openAMErrorResponse.getCode() + " - Reason : " + openAMErrorResponse.getReason() + " - Message : " + openAMErrorResponse.getMessage()); } super.logout(openAMAuthenticate.getTokenId()); return this.openAMReader.readValue(response.getEntity().getContent(), OpenAMGroupResponse.class); }
From source file:com.anitech.resting.Resting.java
/** * Executes a HTTP PUT request with provided configuration * /* w ww . ja v a 2s. c o m*/ * @param endpointUrl * @param inputParams * @throws RestingException */ public RestingResponse PUT(String endpointUrl, Object inputParams, RequestConfig config) throws RestingException { logger.debug("Inside PUT!"); long startTime = System.nanoTime(); // override the request config config = RestingUtil.overrideGlobalRequestConfig(globalRequestConfig, config); httpClient = HttpClients.createDefault(); try { org.apache.http.client.config.RequestConfig requestConfig = org.apache.http.client.config.RequestConfig .custom().setSocketTimeout(config.getSocketTimeout()) .setConnectTimeout(config.getConnectTimeout()).build(); String fullURL = baseURI + endpointUrl; HttpPut put = new HttpPut(fullURL); put.setConfig(requestConfig); put.setEntity(RequestDataMassager.massageRequestData(inputParams, config)); HttpResponse res = httpClient.execute(put); RestingResponse response = new RestingResponse(res); if (enableMetrics) { long stopTime = System.nanoTime(); long elapsedTime = (stopTime - startTime) / 1000000; logger.fatal("Time taken to execute [PUT - " + fullURL + "] in milliseconds>> " + elapsedTime); } return response; } catch (ClientProtocolException cpe) { cpe.printStackTrace(); throw new RestingException(cpe); } catch (IOException ioe) { ioe.printStackTrace(); throw new RestingException(ioe); } }
From source file:ch.ifocusit.livingdoc.plugin.publish.confluence.client.HttpRequestFactory.java
HttpPut updatePageRequest(String contentId, String ancestorId, String title, String content, int newVersion) { assertMandatoryParameter(isNotBlank(contentId), "contentId"); assertMandatoryParameter(isNotBlank(ancestorId), "ancestorId"); assertMandatoryParameter(isNotBlank(title), "title"); PagePayload pagePayload = pagePayloadBuilder().ancestorId(ancestorId).title(title).content(content) .version(newVersion).build(); HttpPut updatePageRequest = new HttpPut(this.confluenceRestApiEndpoint + "/content/" + contentId); updatePageRequest.setEntity(httpEntityWithJsonPayload(pagePayload)); updatePageRequest.addHeader(APPLICATION_JSON_UTF8_HEADER); return updatePageRequest; }
From source file:com.urbancode.ud.client.ComponentClient.java
public UUID createComponent(String componentName, String description, String sourceConfigPlugin, String defaultVersionType, String templateName, int templateVersion, boolean importAutomatically, boolean useVfs, Map<String, String> properties) throws JSONException, IOException { UUID result = null;/*from ww w . ja v a 2 s . c om*/ JSONObject jsonToSend = new JSONObject(); //put required data jsonToSend.put("name", componentName); jsonToSend.put("sourceConfigPlugin", sourceConfigPlugin); //must be FULL or INCREMENTAL jsonToSend.put("defaultVersionType", defaultVersionType.toUpperCase()); jsonToSend.put("importAutomatically", importAutomatically); jsonToSend.put("useVfs", useVfs); //put optional data if (!"".equals(description) && description != null) { jsonToSend.put("description", description); } if (!"".equals(templateName) && templateName != null) { jsonToSend.put("templateName", templateName); } if (templateVersion > 0) { jsonToSend.put("templateVersion", templateVersion); } JSONObject propertiesObject = new JSONObject(); if (properties != null && !properties.isEmpty()) { for (Entry<String, String> ent : properties.entrySet()) { propertiesObject.put(ent.getKey(), ent.getValue()); } } jsonToSend.put("properties", propertiesObject); String uri = url + "/cli/component/create"; HttpPut method = new HttpPut(uri); method.setEntity(getStringEntity(jsonToSend)); HttpResponse response = invokeMethod(method); String body = getBody(response); JSONObject jsonResult = new JSONObject(body); result = UUID.fromString((String) jsonResult.get("id")); return result; }
From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java
@Test public void testPutConsumer() throws Exception { HttpPut put = new HttpPut("http://localhost:" + PORT1 + "/customerservice/customers"); StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); put.setEntity(entity); HttpClient httpclient = new DefaultHttpClient(); try {//from www. j a v a 2 s .c o m HttpResponse response = httpclient.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("", EntityUtils.toString(response.getEntity())); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.caratarse.auth.services.controller.UserAuthorizationControllerTest.java
@Test public void updateAuthorizationToUser() throws UnsupportedEncodingException, IOException { HttpPut putRequest = new HttpPut( BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c/authorizations/ROLE_PRINTER.json"); StringEntity input = new StringEntity( "{\"permissions\":{ \"read\": true, \"write\": false, \"execute\": false}}"); input.setContentType("application/json"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); assertEquals(204, response.getStatusLine().getStatusCode()); HttpGet getRequest = new HttpGet( BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c/authorizations/ROLE_PRINTER.json"); response = httpClient.execute(getRequest); assertEquals(200, response.getStatusLine().getStatusCode()); log.debug(IOUtils.toString(response.getEntity().getContent())); }
From source file:edu.washington.iam.tools.WebClient.java
public Element doRestPut(String url, List<NameValuePair> data, String auth) { closeIdleConnections();// www . j a v a 2 s . c o m log.debug("do rest put"); Element ele = null; if (restclient == null) restclient = new DefaultHttpClient((ClientConnectionManager) connectionManager, new BasicHttpParams()); try { log.debug(" rest url: " + url); HttpPut httpput = new HttpPut(url); if (auth != null) httpput.addHeader("Authorization", auth); httpput.setEntity(new UrlEncodedFormEntity(data)); CloseableHttpResponse response = restclient.execute(httpput); log.debug("resp: " + response.getStatusLine().getStatusCode() + " = " + response.getStatusLine().getReasonPhrase()); HttpEntity entity = response.getEntity(); // null is error - should get something if (entity == null) { response.close(); throw new WebClientException("restclient post exception"); } // parse response text Document doc = documentBuilder.parse(entity.getContent()); ele = doc.getDocumentElement(); response.close(); } catch (Exception e) { log.error("exception " + e); } return ele; }