Java Code Examples for org.springframework.http.HttpHeaders#setContentLength()

The following examples show how to use org.springframework.http.HttpHeaders#setContentLength() . 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: RestTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void postForEntityNull() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "http://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(StreamUtils.emptyInput());
	given(converter.read(String.class, response)).willReturn(null);

	ResponseEntity<String> result = template.postForEntity("http://example.com", null, String.class);
	assertFalse("Invalid POST result", result.hasBody());
	assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
	assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example 2
Source File: WorkspaceController.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping(value = "/workspaces/{spaceKey}/raw", method = GET)
public ResponseEntity<InputStreamResource> raw(@PathVariable("spaceKey") Workspace ws,
                                               @RequestParam String path,
                                               @RequestParam(defaultValue = "true") Boolean inline) throws Exception {


    FileInfo fileInfo = wsMgr.getFileInfo(ws, path);

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.valueOf(fileInfo.getContentType()));
    headers.setContentLength(fileInfo.getSize());

    if (inline) {
        headers.add(CONTENT_DISPOSITION, format("inline; filename='%s'", encodeFileName(fileInfo.getName())));
    } else {
        headers.add(CONTENT_DISPOSITION, format("attachment; filename='%s'", encodeFileName(fileInfo.getName())));
    }

    InputStreamResource inputStreamResource = new InputStreamResource(ws.getInputStream(path));

    return ResponseEntity.ok()
            .headers(headers)
            .body(inputStreamResource);
}
 
Example 3
Source File: ExtractingResponseErrorHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handleErrorSeriesMatch() throws Exception {
	given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.APPLICATION_JSON);
	given(this.response.getHeaders()).willReturn(responseHeaders);

	byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
	responseHeaders.setContentLength(body.length);
	given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));

	try {
		this.errorHandler.handleError(this.response);
		fail("MyRestClientException expected");
	}
	catch (MyRestClientException ex) {
		assertEquals("bar", ex.getFoo());
	}
}
 
Example 4
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void patchForObjectNull() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(PATCH, "https://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(StreamUtils.emptyInput());

	String result = template.patchForObject("https://example.com", null, String.class);
	assertNull("Invalid POST result", result);
	assertEquals("Invalid content length", 0, requestHeaders.getContentLength());

	verify(response).close();
}
 
Example 5
Source File: AbstractHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Add default headers to the output message.
 * <p>This implementation delegates to {@link #getDefaultContentType(Object)} if a content
 * type was not provided, calls {@link #getContentLength}, and sets the corresponding headers
 * @since 4.2
 */
protected void addDefaultHeaders(HttpHeaders headers, T t, MediaType contentType) throws IOException{
	if (headers.getContentType() == null) {
		MediaType contentTypeToUse = contentType;
		if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
			contentTypeToUse = getDefaultContentType(t);
		}
		else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
			MediaType mediaType = getDefaultContentType(t);
			contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
		}
		if (contentTypeToUse != null) {
			headers.setContentType(contentTypeToUse);
		}
	}
	if (headers.getContentLength() == -1) {
		Long contentLength = getContentLength(t, headers.getContentType());
		if (contentLength != null) {
			headers.setContentLength(contentLength);
		}
	}
}
 
Example 6
Source File: ModifyRequestBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
		CachedBodyOutputMessage outputMessage) {
	return new ServerHttpRequestDecorator(exchange.getRequest()) {
		@Override
		public HttpHeaders getHeaders() {
			long contentLength = headers.getContentLength();
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.putAll(headers);
			if (contentLength > 0) {
				httpHeaders.setContentLength(contentLength);
			}
			else {
				// TODO: this causes a 'HTTP/1.1 411 Length Required' // on
				// httpbin.org
				httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
			}
			return httpHeaders;
		}

		@Override
		public Flux<DataBuffer> getBody() {
			return outputMessage.getBody();
		}
	};
}
 
Example 7
Source File: ExtractingResponseErrorHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleErrorSeriesMatch() throws Exception {
	given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.APPLICATION_JSON);
	given(this.response.getHeaders()).willReturn(responseHeaders);

	byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
	responseHeaders.setContentLength(body.length);
	given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));

	try {
		this.errorHandler.handleError(this.response);
		fail("MyRestClientException expected");
	}
	catch (MyRestClientException ex) {
		assertEquals("bar", ex.getFoo());
	}
}
 
Example 8
Source File: RadarServerController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
HttpEntity<byte[]> simpleString(String str) {
  byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
  HttpHeaders header = new HttpHeaders();
  header.setContentType(new MediaType("application", "text"));
  header.setContentLength(bytes.length);
  return new HttpEntity<>(bytes, header);
}
 
Example 9
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void mockResponseBody(String expectedBody, MediaType mediaType) throws Exception {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(mediaType);
	responseHeaders.setContentLength(expectedBody.length());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expectedBody.getBytes()));
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expectedBody);
}
 
Example 10
Source File: FlatNetworkServiceSimulator.java    From zstack with Apache License 2.0 5 votes vote down vote up
public void reply(HttpEntity<String> entity, Object rsp) {
    String taskUuid = entity.getHeaders().getFirst(RESTConstant.TASK_UUID);
    String callbackUrl = entity.getHeaders().getFirst(RESTConstant.CALLBACK_URL);
    String rspBody = JSONObjectUtil.toJsonString(rsp);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setContentLength(rspBody.length());
    headers.set(RESTConstant.TASK_UUID, taskUuid);
    HttpEntity<String> rreq = new HttpEntity<String>(rspBody, headers);
    restf.getRESTTemplate().exchange(callbackUrl, HttpMethod.POST, rreq, String.class);
}
 
Example 11
Source File: RestTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void getUnsupportedMediaType() throws Exception {
	given(converter.canRead(String.class, null)).willReturn(true);
	MediaType supportedMediaType = new MediaType("foo", "bar");
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
	given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request);
	HttpHeaders requestHeaders = new HttpHeaders();
	given(request.getHeaders()).willReturn(requestHeaders);
	given(request.execute()).willReturn(response);
	given(errorHandler.hasError(response)).willReturn(false);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = new MediaType("bar", "baz");
	responseHeaders.setContentType(contentType);
	responseHeaders.setContentLength(10);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foo".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(false);
	HttpStatus status = HttpStatus.OK;
	given(response.getStatusCode()).willReturn(status);
	given(response.getStatusText()).willReturn(status.getReasonPhrase());

	try {
		template.getForObject("http://example.com/{p}", String.class, "resource");
		fail("UnsupportedMediaTypeException expected");
	}
	catch (RestClientException ex) {
		// expected
	}

	verify(response).close();
}
 
Example 12
Source File: HttpMessageConverterExtractorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void zeroContentLength() throws IOException {
	HttpMessageConverter<?> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentLength(0);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);

	Object result = extractor.extractData(response);
	assertNull(result);
}
 
Example 13
Source File: SMPPrimaryStorageSimulator.java    From zstack with Apache License 2.0 5 votes vote down vote up
public void reply(HttpEntity<String> entity, Object rsp) {
    String taskUuid = entity.getHeaders().getFirst(RESTConstant.TASK_UUID);
    String callbackUrl = entity.getHeaders().getFirst(RESTConstant.CALLBACK_URL);
    String rspBody = JSONObjectUtil.toJsonString(rsp);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setContentLength(rspBody.length());
    headers.set(RESTConstant.TASK_UUID, taskUuid);
    HttpEntity<String> rreq = new HttpEntity<String>(rspBody, headers);
    restf.getRESTTemplate().exchange(callbackUrl, HttpMethod.POST, rreq, String.class);
}
 
Example 14
Source File: ExportController.java    From microcks with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/export", method = RequestMethod.GET)
public ResponseEntity<?> exportRepository(@RequestParam(value = "serviceIds") List<String> serviceIds) {
   log.debug("Extracting export for serviceIds {}", serviceIds);
   String json = importExportService.exportRepository(serviceIds, "json");

   byte[] body = json.getBytes();
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setContentType(MediaType.APPLICATION_JSON);
   responseHeaders.set("Content-Disposition", "attachment; filename=microcks-repository.json");
   responseHeaders.setContentLength(body.length);

   return new ResponseEntity<Object>(body, responseHeaders, HttpStatus.OK);
}
 
Example 15
Source File: AeroRemoteApiController.java    From webanno with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "Export a project to a ZIP file")
@RequestMapping(
        value = ("/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + EXPORT), 
        method = RequestMethod.GET,
        produces = { "application/zip", APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<InputStreamResource> projectExport(
        @PathVariable(PARAM_PROJECT_ID) long aProjectId,
        @RequestParam(value = PARAM_FORMAT) Optional<String> aFormat)
    throws Exception
{
    // Get project (this also ensures that it exists and that the current user can access it
    Project project = getProject(aProjectId);
    
    // Check if the format is supported
    if (aFormat.isPresent()) {
        importExportService.getWritableFormatById(aFormat.get())
                .orElseThrow(() -> new UnsupportedFormatException(
                        "Format [%s] cannot be exported. Exportable formats are %s.", 
                        aFormat.get(), importExportService.getWritableFormats().stream()
                                .map(FormatSupport::getId)
                                .sorted()
                                .collect(Collectors.toList()).toString()));
    }
    
    ProjectExportRequest request = new ProjectExportRequest(project,
            aFormat.orElse(WebAnnoTsv3FormatSupport.ID), true);
    ProjectExportTaskMonitor monitor = new ProjectExportTaskMonitor();
    File exportedFile = exportService.exportProject(request, monitor);
    
    // Turn the file into a resource and auto-delete the file when the resource closes the
    // stream.
    InputStreamResource result = new InputStreamResource(new FileInputStream(exportedFile) {
        @Override
        public void close() throws IOException
        {
            super.close();
            FileUtils.forceDelete(exportedFile);
        } 
    });

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf("application/zip"));
    httpHeaders.setContentLength(exportedFile.length());
    httpHeaders.set("Content-Disposition",
            "attachment; filename=\"" + exportedFile.getName() + "\"");

    return new ResponseEntity<>(result, httpHeaders, HttpStatus.OK);
}
 
Example 16
Source File: FastJsonHttpMessageConverter.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    ByteArrayOutputStream outnew = new ByteArrayOutputStream();
    try {
        HttpHeaders headers = outputMessage.getHeaders();

        //获取全局配置的filter
        SerializeFilter[] globalFilters = fastJsonConfig.getSerializeFilters();
        List<SerializeFilter> allFilters = new ArrayList<SerializeFilter>(Arrays.asList(globalFilters));

        boolean isJsonp = false;

        //不知道为什么会有这行代码, 但是为了保持和原来的行为一致,还是保留下来
        Object value = strangeCodeForJackson(object);

        if (value instanceof FastJsonContainer) {
            FastJsonContainer fastJsonContainer = (FastJsonContainer) value;
            PropertyPreFilters filters = fastJsonContainer.getFilters();
            allFilters.addAll(filters.getFilters());
            value = fastJsonContainer.getValue();
        }

        //revise 2017-10-23 ,
        // 保持原有的MappingFastJsonValue对象的contentType不做修改 保持旧版兼容。
        // 但是新的JSONPObject将返回标准的contentType:application/javascript ,不对是否有function进行判断
        if (value instanceof MappingFastJsonValue) {
            if(!StringUtils.isEmpty(((MappingFastJsonValue) value).getJsonpFunction())){
                isJsonp = true;
            }
        } else if (value instanceof JSONPObject) {
            isJsonp = true;
        }


        int len = JSON.writeJSONString(outnew, //
                fastJsonConfig.getCharset(), //
                value, //
                fastJsonConfig.getSerializeConfig(), //
                //fastJsonConfig.getSerializeFilters(), //
                allFilters.toArray(new SerializeFilter[allFilters.size()]),
                fastJsonConfig.getDateFormat(), //
                JSON.DEFAULT_GENERATE_FEATURE, //
                fastJsonConfig.getSerializerFeatures());

        if (isJsonp) {
            headers.setContentType(APPLICATION_JAVASCRIPT);
        }

        if (fastJsonConfig.isWriteContentLength()) {
            headers.setContentLength(len);
        }

        outnew.writeTo(outputMessage.getBody());

    } catch (JSONException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    } finally {
        outnew.close();
    }
}
 
Example 17
Source File: HttpResponse.java    From charon-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
public void setBody(byte[] body) {
    this.body = body;
    HttpHeaders rewrittenHeaders = copyHeaders(headers);
    rewrittenHeaders.setContentLength(body.length);
    setHeaders(rewrittenHeaders);
}
 
Example 18
Source File: HttpResponse.java    From charon-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
public void setBody(byte[] body) {
    this.body = just(body);
    HttpHeaders rewrittenHeaders = copyHeaders(delegate.headers().asHttpHeaders());
    rewrittenHeaders.setContentLength(body.length);
    setHeaders(rewrittenHeaders);
}
 
Example 19
Source File: RadarServerController.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private HttpEntity<byte[]> makeCatalog(String dataset, RadarDataInventory inv, RadarDataInventory.Query query,
    String queryString) throws IOException, ParseException {
  Collection<RadarDataInventory.Query.QueryResultItem> res = query.results();
  CatalogBuilder cb = new CatalogBuilder();

  // At least the IDV needs to have the trailing slash included
  if (!dataset.endsWith("/"))
    dataset += "/";

  Service dap = new Service("OPENDAP", "/thredds/dodsC/" + dataset, ServiceType.OPENDAP.toString(),
      ServiceType.OPENDAP.getDescription(), null, new ArrayList<Service>(), new ArrayList<Property>(),
      ServiceType.OPENDAP.getAccessType());
  Service cdmr = new Service("CDMRemote", "/thredds/cdmremote/" + dataset, ServiceType.CdmRemote.toString(),
      ServiceType.CdmRemote.getDescription(), null, new ArrayList<Service>(), new ArrayList<Property>(),
      ServiceType.CdmRemote.getAccessType());
  Service files = new Service("HTTPServer", "/thredds/fileServer/" + dataset, ServiceType.HTTPServer.toString(),
      ServiceType.HTTPServer.getDescription(), null, new ArrayList<Service>(), new ArrayList<Property>(),
      ServiceType.HTTPServer.getAccessType());
  cb.addService(
      new Service("RadarServices", "", ServiceType.Compound.toString(), ServiceType.Compound.getDescription(), null,
          Arrays.asList(dap, files, cdmr), new ArrayList<Property>(), ServiceType.Compound.getAccessType()));
  cb.setName("Radar " + inv.getName() + " datasets in near real time");

  DatasetBuilder mainDB = new DatasetBuilder(null);
  mainDB.setName("Radar" + inv.getName() + " datasets for available stations and times");
  mainDB.put(Dataset.CollectionType, "TimeSeries");
  mainDB.put(Dataset.Id, queryString);

  ThreddsMetadata tmd = new ThreddsMetadata();
  Map<String, Object> metadata = tmd.getFlds();
  metadata.put(Dataset.DataFormatType, inv.getDataFormat());
  metadata.put(Dataset.FeatureType, inv.getFeatureType().toString());
  metadata.put(Dataset.ServiceName, "RadarServices");
  metadata.put(Dataset.Documentation,
      new Documentation(null, null, null, null, res.size() + " datasets found for query"));

  mainDB.put(Dataset.ThreddsMetadataInheritable, tmd);

  for (RadarDataInventory.Query.QueryResultItem i : res) {
    DatasetBuilder fileDB = new DatasetBuilder(mainDB);
    fileDB.setName(i.file.getFileName().toString());
    fileDB.put(Dataset.Id, String.valueOf(i.file.hashCode()));

    fileDB.put(Dataset.Dates, new DateType(i.time.toString(), null, "start of ob", i.time.getCalendar()));

    // TODO: Does this need to be converted from the on-disk path
    // to a mapped url path?
    fileDB.put(Dataset.UrlPath, inv.getCollectionDir().relativize(i.file).toString());
    mainDB.addDataset(fileDB);
  }

  cb.addDataset(mainDB);

  CatalogXmlWriter writer = new CatalogXmlWriter();
  ByteArrayOutputStream os = new ByteArrayOutputStream(10000);
  writer.writeXML(cb.makeCatalog(), os);
  byte[] xmlBytes = os.toByteArray();

  HttpHeaders header = new HttpHeaders();
  header.setContentType(new MediaType("application", "xml"));
  header.setContentLength(xmlBytes.length);
  return new HttpEntity<>(xmlBytes, header);
}
 
Example 20
Source File: JsonMessageConverter.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    try (ByteArrayOutputStream outnew = new ByteArrayOutputStream()) {
        HttpHeaders headers = outputMessage.getHeaders();

        //获取全局配置的filter
        SerializeFilter[] globalFilters = getFastJsonConfig().getSerializeFilters();
        List<SerializeFilter> allFilters = new ArrayList<>(Arrays.asList(globalFilters));

        boolean isJsonp = false;
        Object value = strangeCodeForJackson(object);

        if (value instanceof FastJsonContainer) {
            FastJsonContainer fastJsonContainer = (FastJsonContainer) value;
            PropertyPreFilters filters = fastJsonContainer.getFilters();
            allFilters.addAll(filters.getFilters());
            value = fastJsonContainer.getValue();
        }

        if (value instanceof MappingFastJsonValue) {
            isJsonp = true;
            value = ((MappingFastJsonValue) value).getValue();
        } else if (value instanceof JSONPObject) {
            isJsonp = true;
        }


        int len = writePrefix(outnew, object);
        len += JSON.writeJSONString(outnew, //
                getFastJsonConfig().getCharset(), //
                value, //
                getFastJsonConfig().getSerializeConfig(), //
                allFilters.toArray(new SerializeFilter[allFilters.size()]),
                getFastJsonConfig().getDateFormat(), //
                JSON.DEFAULT_GENERATE_FEATURE, //
                getFastJsonConfig().getSerializerFeatures());
        len += writeSuffix(outnew, object);

        if (isJsonp) {
            headers.setContentType(APPLICATION_JAVASCRIPT);
        }
        if (getFastJsonConfig().isWriteContentLength()) {
            headers.setContentLength(len);
        }

        headers.set("carrera_logid", RequestContext.getLogId());
        RequestContext.sendJsonResponse(outnew.toString());

        outnew.writeTo(outputMessage.getBody());

    } catch (JSONException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}