List of usage examples for org.apache.http.entity StringEntity setChunked
public void setChunked(boolean z)
From source file:org.openhim.mediator.engine.MediatorServerTest.java
private CloseableHttpResponse executeHTTPRequest(String method, String path, String body, Map<String, String> headers, Map<String, String> params) throws URISyntaxException, IOException { URIBuilder builder = new URIBuilder().setScheme("http").setHost(testConfig.getServerHost()) .setPort(testConfig.getServerPort()).setPath(path); if (params != null) { Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { String param = iter.next(); builder.addParameter(param, params.get(param)); }// w w w . j a v a 2 s. com } HttpUriRequest uriReq; switch (method) { case "GET": uriReq = new HttpGet(builder.build()); break; case "POST": uriReq = new HttpPost(builder.build()); StringEntity entity = new StringEntity(body); if (body.length() > 1024) { //always test big requests chunked entity.setChunked(true); } ((HttpPost) uriReq).setEntity(entity); break; case "PUT": uriReq = new HttpPut(builder.build()); StringEntity putEntity = new StringEntity(body); ((HttpPut) uriReq).setEntity(putEntity); break; case "DELETE": uriReq = new HttpDelete(builder.build()); break; default: throw new UnsupportedOperationException(method + " requests not supported"); } if (headers != null) { Iterator<String> iter = headers.keySet().iterator(); while (iter.hasNext()) { String header = iter.next(); uriReq.addHeader(header, headers.get(header)); } } RequestConfig.Builder reqConf = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(1000); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(reqConf.build()).build(); CloseableHttpResponse response = client.execute(uriReq); boolean foundContentType = false; for (Header hdr : response.getAllHeaders()) { if ("content-type".equalsIgnoreCase(hdr.getName())) { assertTrue(hdr.getValue().contains("application/json+openhim")); foundContentType = true; } } assertTrue("Content-Type must be included in the response", foundContentType); return response; }
From source file:org.fcrepo.test.api.TestAdminAPI.java
private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;//from ww w. j a va 2 s. co m } HttpEntityEnclosingRequestBase httpMethod = null; try { if (method.equals("PUT")) { httpMethod = new HttpPut(url); } else if (method.equals("POST")) { httpMethod = new HttpPost(url); } else { throw new IllegalArgumentException("method must be one of PUT or POST."); } httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive"); if (requestContent != null) { if (requestContent instanceof String) { StringEntity entity = new StringEntity((String) requestContent, Charset.forName("UTF-8")); entity.setChunked(chunked); httpMethod.setEntity(entity); } else if (requestContent instanceof File) { MultipartEntity entity = new MultipartEntity(); entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent)); entity.addPart("param_name", new StringBody("value")); httpMethod.setEntity(entity); } else { throw new IllegalArgumentException("requestContent must be a String or File"); } } return getClient(authenticate).execute(httpMethod); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:com.biomeris.i2b2.export.ws.ExportService.java
private boolean validateUser(Network network) throws JAXBException, IOException, TransformerException { boolean output = false; String pmRequest = MessageBuilder.buildPMGetServiceRequest(network); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(network.getProxyAddress()); StringEntity entity1A = new StringEntity(pmRequest, Consts.UTF_8); entity1A.setContentType("text/xml"); entity1A.setChunked(true); httpPost.setEntity(entity1A);//ww w. ja v a2 s . com CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost); log.debug("Proxy: " + network.getProxyAddress()); } catch (HttpHostConnectException hhce) { try { if (network.getStaticProxyAddress() != null) { httpPost = new HttpPost(network.getStaticProxyAddress()); httpPost.setEntity(entity1A); response = httpclient.execute(httpPost); log.debug("Proxy: " + network.getStaticProxyAddress()); } } catch (HttpHostConnectException e) { throw e; } } try { HttpEntity entity1R = response.getEntity(); String responseString = EntityUtils.toString(entity1R); ResponseMessageType rmt = JAXB.unmarshal(new StringReader(responseString), ResponseMessageType.class); ResponseHeaderType responseHeader = rmt.getResponseHeader(); ResultStatusType responseStatus = responseHeader.getResultStatus(); if (responseStatus.getStatus().getType().equals("ERROR")) { return false; } BodyType body = rmt.getMessageBody(); ElementNSImpl bodyEl = (ElementNSImpl) body.getAny().get(0); String bodyStr = elementToString(bodyEl); ConfigureType configureType = JAXB.unmarshal(new StringReader(bodyStr), ConfigureType.class); UserType userType = configureType.getUser(); if (userType.isIsAdmin()) { output = true; } else { List<ProjectType> userProjects = userType.getProject(); for (ProjectType pt : userProjects) { if (pt.getId().equals(network.getProject())) { if (userAccessLevel(pt.getRole()) >= authLevel) { output = true; } } } } EntityUtils.consume(entity1R); } finally { response.close(); } return output; }
From source file:de.tu_dortmund.ub.data.dswarm.Transform.java
/** * configuration and processing of the task * * @param inputDataModelID/* w w w . j a v a2 s. com*/ * @param projectIDs * @param outputDataModelID * @return */ private String executeTask(final String inputDataModelID, final Collection<String> projectIDs, final String outputDataModelID, final String serviceName, final String engineDswarmAPI, final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly, final Optional<String> optionalExportMimeType, final Optional<String> optionalExportFileExtension) throws Exception { final JsonArray mappings = getMappingsFromProjects(projectIDs, serviceName, engineDswarmAPI); final JsonObject inputDataModel = getDataModel(inputDataModelID, serviceName, engineDswarmAPI); final JsonObject outputDataModel = getDataModel(outputDataModelID, serviceName, engineDswarmAPI); final Optional<JsonObject> optionalSkipFilter = getSkipFilter(serviceName, engineDswarmAPI); // erzeuge Task-JSON final String persistString = config.getProperty(TPUStatics.PERSIST_IN_DMP_IDENTIFIER); final boolean persist; if (persistString != null && !persistString.trim().isEmpty()) { persist = Boolean.valueOf(persistString); } else { // default is false persist = false; } final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DswarmBackendStatics.PERSIST_IDENTIFIER, persist); // default for now: true, i.e., no content will be returned jp.write(DswarmBackendStatics.DO_NOT_RETURN_DATA_IDENTIFIER, true); // default for now: true, i.e., if a schema is attached it will utilised (instead of being derived from the data resource) jp.write(DswarmBackendStatics.UTILISE_EXISTING_INPUT_IDENTIFIER, true); if (optionalDoIngestOnTheFly.isPresent()) { final Boolean doIngestOnTheFly = optionalDoIngestOnTheFly.get(); if (doIngestOnTheFly) { LOG.info(String.format("[%s][%d] do ingest on-the-fly", serviceName, cnt)); } jp.write(DswarmBackendStatics.DO_INGEST_ON_THE_FLY, doIngestOnTheFly); } if (optionalDoExportOnTheFly.isPresent()) { final Boolean doExportOnTheFly = optionalDoExportOnTheFly.get(); if (doExportOnTheFly) { LOG.info(String.format("[%s][%d] do export on-the-fly", serviceName, cnt)); } jp.write(DswarmBackendStatics.DO_EXPORT_ON_THE_FLY, doExportOnTheFly); } jp.write(DswarmBackendStatics.DO_VERSIONING_ON_RESULT_IDENTIFIER, false); // task jp.writeStartObject(DswarmBackendStatics.TASK_IDENTIFIER); jp.write(DswarmBackendStatics.NAME_IDENTIFIER, "Task Batch-Prozess 'CrossRef'"); jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, "Task Batch-Prozess 'CrossRef' zum InputDataModel 'inputDataModelID '"); // job jp.writeStartObject(DswarmBackendStatics.JOB_IDENTIFIER); jp.write(DswarmBackendStatics.UUID_IDENTIFIER, UUID.randomUUID().toString()); jp.write(DswarmBackendStatics.MAPPINGS_IDENTIFIER, mappings); if (optionalSkipFilter.isPresent()) { jp.write(DswarmBackendStatics.SKIP_FILTER_IDENTIFIER, optionalSkipFilter.get()); } jp.writeEnd(); jp.write(DswarmBackendStatics.INPUT_DATA_MODEL_IDENTIFIER, inputDataModel); jp.write(DswarmBackendStatics.OUTPUT_DATA_MODEL_IDENTIFIER, outputDataModel); // end task jp.writeEnd(); // end request jp.writeEnd(); jp.flush(); jp.close(); final String task = stringWriter.toString(); stringWriter.flush(); stringWriter.close(); LOG.debug(String.format("[%s][%d] task : %s", serviceName, cnt, task)); try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { // POST /dmp/tasks/ final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.TASKS_ENDPOINT); final StringEntity stringEntity = new StringEntity(task, ContentType.APPLICATION_JSON); stringEntity.setChunked(true); final String mimetype; if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { if (optionalExportMimeType.isPresent()) { mimetype = optionalExportMimeType.get(); } else { // default export mime type is XML mimetype = APIStatics.APPLICATION_XML_MIMETYPE; } } else { mimetype = APIStatics.APPLICATION_JSON_MIMETYPE; } httpPost.setHeader(HttpHeaders.ACCEPT, mimetype); //httpPost.setHeader(HttpHeaders.TRANSFER_ENCODING, CHUNKED_TRANSFER_ENCODING); httpPost.setEntity(stringEntity); final Header[] requestHeaders = httpPost.getAllHeaders(); final String printedRequestHeaders = printHeaders(requestHeaders); LOG.info(String.format("[%s][%d] request : %s :: request headers : \n'%s' :: body : '%s'", serviceName, cnt, httpPost.getRequestLine(), printedRequestHeaders, stringEntity)); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final Header[] responseHeaders = httpResponse.getAllHeaders(); final String printedResponseHeaders = printHeaders(responseHeaders); LOG.info(String.format("[%s][%d] response headers : \n'%s'", serviceName, cnt, printedResponseHeaders)); final int statusCode = httpResponse.getStatusLine().getStatusCode(); switch (statusCode) { case 204: { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); EntityUtils.consume(httpResponse.getEntity()); return "success"; } case 200: { if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); final String exportFileExtension; if (optionalExportFileExtension.isPresent()) { exportFileExtension = optionalExportFileExtension.get(); } else { // XML as default file ending exportFileExtension = TaskProcessingUnit.XML_FILE_ENDING; } // write result to file final String fileName = TPUUtil.writeResultToFile(httpResponse, config, outputDataModelID + "-" + inputDataModelID + "-" + cnt, exportFileExtension); return "success - exported XML to '" + fileName + "'"; } } default: { LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); final String response = TPUUtil.getResponseMessage(httpResponse); throw new Exception("something went wrong at task execution" + response); } } } } }
From source file:at.ac.tuwien.dsg.comot.orchestrator.interraction.rsybl.rSYBLInterraction.java
public void sendUpdatedConfigToRSYBL(CloudService serviceTemplate, CompositionRulesConfiguration compositionRulesConfiguration, String effectsJSON) { HttpHost endpoint = new HttpHost(rSYBL_BASE_IP, rSYBL_BASE_PORT); {/*from w ww .j a v a2 s. c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); try { JAXBContext jAXBContext = JAXBContext.newInstance(CompositionRulesConfiguration.class); Marshaller marshaller = jAXBContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); log.info("Sending updated composition rules"); marshaller.marshal(compositionRulesConfiguration, sw); log.info(sw.toString()); URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/compositionRules").build(); HttpPost putDeployment = new HttpPost(putDeploymentStructureURL); StringEntity entity = new StringEntity(sw.getBuffer().toString()); entity.setContentType("application/xml"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Executing request " + putDeployment.getRequestLine()); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityCapabilitiesEffects") .build(); HttpPost putDeployment = new HttpPost(putDeploymentStructureURL); StringEntity entity = new StringEntity(effectsJSON); entity.setContentType("application/json"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Send updated Effects"); log.info(effectsJSON); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { JAXBContext jAXBContext = JAXBContext.newInstance(CloudServiceXML.class); CloudServiceXML cloudServiceXML = toRSYBLRepresentation(serviceTemplate); Marshaller marshaller = jAXBContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); log.info("Sending updated service description to rSYBL"); marshaller.marshal(cloudServiceXML, sw); log.info(sw.toString()); URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityRequirements") .build(); HttpPost putDeployment = new HttpPost(putDeploymentStructureURL); StringEntity entity = new StringEntity(sw.getBuffer().toString()); entity.setContentType("application/xml"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Executing request " + putDeployment.getRequestLine()); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } }
From source file:at.ac.tuwien.dsg.comot.orchestrator.interraction.rsybl.rSYBLInterraction.java
public void sendInitialConfigToRSYBL(CloudService serviceTemplate, DeploymentDescription deploymentDescription, CompositionRulesConfiguration compositionRulesConfiguration, String effectsJSON) { deploymentDescription = enrichWithElasticityCapabilities(deploymentDescription, serviceTemplate); HttpHost endpoint = new HttpHost(rSYBL_BASE_IP, rSYBL_BASE_PORT); {/*from ww w .j a va2 s . co m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); URI prepareConfigURI = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/prepareControl").build(); HttpPut prepareConfig = new HttpPut(prepareConfigURI); try { HttpResponse httpResponse = httpClient.execute(endpoint, prepareConfig); EntityUtils.consume(httpResponse.getEntity()); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { JAXBContext jAXBContext = JAXBContext.newInstance(DeploymentDescription.class); Marshaller marshaller = jAXBContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); log.info("Sending deployment description to rSYBL"); marshaller.marshal(deploymentDescription, sw); log.info(sw.toString()); URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/deployment").build(); HttpPut putDeployment = new HttpPut(putDeploymentStructureURL); StringEntity entity = new StringEntity(sw.getBuffer().toString()); entity.setContentType("application/xml"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Executing request " + putDeployment.getRequestLine()); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { JAXBContext jAXBContext = JAXBContext.newInstance(CloudServiceXML.class); CloudServiceXML cloudServiceXML = toRSYBLRepresentation(serviceTemplate); Marshaller marshaller = jAXBContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); log.info("Sending service description description to rSYBL"); marshaller.marshal(cloudServiceXML, sw); log.info(sw.toString()); URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/description").build(); HttpPut putDeployment = new HttpPut(putDeploymentStructureURL); StringEntity entity = new StringEntity(sw.getBuffer().toString()); entity.setContentType("application/xml"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Executing request " + putDeployment.getRequestLine()); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { JAXBContext jAXBContext = JAXBContext.newInstance(CompositionRulesConfiguration.class); Marshaller marshaller = jAXBContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); log.info("Sending updated composition rules"); marshaller.marshal(compositionRulesConfiguration, sw); log.info(sw.toString()); URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/compositionRules").build(); HttpPut putDeployment = new HttpPut(putDeploymentStructureURL); StringEntity entity = new StringEntity(sw.getBuffer().toString()); entity.setContentType("application/xml"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Executing request " + putDeployment.getRequestLine()); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); try { URI putDeploymentStructureURL = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityCapabilitiesEffects") .build(); HttpPut putDeployment = new HttpPut(putDeploymentStructureURL); String jsonEffectsDescription = capabilitiesToJSON(serviceTemplate); StringEntity entity = new StringEntity(jsonEffectsDescription); entity.setContentType("application/json"); entity.setChunked(true); putDeployment.setEntity(entity); log.info("Send updated Effects"); log.info(effectsJSON); HttpResponse response = httpClient.execute(endpoint, putDeployment); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { } if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } } catch (Exception e) { log.error(e.getMessage(), e); } } { DefaultHttpClient httpClient = new DefaultHttpClient(); URI prepareConfigURI = UriBuilder .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/startControl").build(); HttpPut prepareConfig = new HttpPut(prepareConfigURI); try { HttpResponse httpResponse = httpClient.execute(endpoint, prepareConfig); EntityUtils.consume(httpResponse.getEntity()); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }
From source file:org.apache.awf.web.SystemTest.java
@Test public void serverChunkedBodyRequest() throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://localhost:" + PORT + "/echo"); StringEntity se = new StringEntity("azertyuiopqsdfghjklmwxc\nvbn1234567890"); se.setChunked(true); httpPost.setEntity(se);/*from w ww. j a va 2s . co m*/ HttpResponse httpResponse = httpclient.execute(httpPost); assertEquals("azertyuiopqsdfghjklmwxc\nvbn1234567890", new String(EntityUtils.toByteArray(httpResponse.getEntity()))); }