org.springframework.http.HttpOutputMessage Java Examples
The following examples show how to use
org.springframework.http.HttpOutputMessage.
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: AbstractJsonHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
@Override protected final void writeInternal(Object o, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Writer writer = getWriter(outputMessage); if (this.jsonPrefix != null) { writer.append(this.jsonPrefix); } try { writeInternal(o, type, writer); } catch (Exception ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } writer.flush(); }
Example #2
Source File: ResourceRegionHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (object instanceof ResourceRegion) { writeResourceRegion((ResourceRegion) object, outputMessage); } else { Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object; if (regions.size() == 1) { writeResourceRegion(regions.iterator().next(), outputMessage); } else { writeResourceRegionCollection((Collection<ResourceRegion>) object, outputMessage); } } }
Example #3
Source File: FormHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException { final byte[] boundary = generateMultipartBoundary(); Map<String, String> parameters = new LinkedHashMap<>(2); if (!isFilenameCharsetSet()) { parameters.put("charset", this.charset.name()); } parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII)); MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters); HttpHeaders headers = outputMessage.getHeaders(); headers.setContentType(contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> { writeParts(outputStream, parts, boundary); writeEnd(outputStream, boundary); }); } else { writeParts(outputMessage.getBody(), parts, boundary); writeEnd(outputMessage.getBody(), boundary); } }
Example #4
Source File: HttpEntityMethodProcessorMockTests.java From spring-analysis-note with MIT License | 6 votes |
@Test //SPR-16754 public void disableRangeSupportForStreamingResponses() throws Exception { InputStream is = new ByteArrayInputStream("Content".getBytes(StandardCharsets.UTF_8)); InputStreamResource resource = new InputStreamResource(is, "test"); ResponseEntity<Resource> returnValue = ResponseEntity.ok(resource); servletRequest.addHeader("Range", "bytes=0-5"); given(resourceMessageConverter.canWrite(any(), eq(null))).willReturn(true); given(resourceMessageConverter.canWrite(any(), eq(APPLICATION_OCTET_STREAM))).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest); then(resourceMessageConverter).should(times(1)).write( any(InputStreamResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); assertEquals(200, servletResponse.getStatus()); assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES), Matchers.isEmptyOrNullString()); }
Example #5
Source File: HttpEntityMethodProcessorMockTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings("unchecked") public void shouldHandleReturnValueWithResponseBodyAdvice() throws Exception { servletRequest.addHeader("Accept", "text/*"); servletRequest.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); ResponseEntity<String> returnValue = new ResponseEntity<>(HttpStatus.OK); ResponseBodyAdvice<String> advice = mock(ResponseBodyAdvice.class); given(advice.supports(any(), any())).willReturn(true); given(advice.beforeBodyWrite(any(), any(), any(), any(), any(), any())).willReturn("Foo"); HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor( Collections.singletonList(stringHttpMessageConverter), null, Collections.singletonList(advice)); reset(stringHttpMessageConverter); given(stringHttpMessageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); verify(stringHttpMessageConverter).write(eq("Foo"), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); }
Example #6
Source File: BufferedImageHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
@Override public void write(final BufferedImage image, @Nullable final MediaType contentType, final HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { final MediaType selectedContentType = getContentType(contentType); outputMessage.getHeaders().setContentType(selectedContentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> writeInternal(image, selectedContentType, outputStream)); } else { writeInternal(image, selectedContentType, outputMessage.getBody()); } }
Example #7
Source File: FormHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException { final byte[] boundary = generateMultipartBoundary(); Map<String, String> parameters = new LinkedHashMap<>(2); if (!isFilenameCharsetSet()) { parameters.put("charset", this.charset.name()); } parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII)); MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters); HttpHeaders headers = outputMessage.getHeaders(); headers.setContentType(contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> { writeParts(outputStream, parts, boundary); writeEnd(outputStream, boundary); }); } else { writeParts(outputMessage.getBody(), parts, boundary); writeEnd(outputMessage.getBody(), boundary); } }
Example #8
Source File: FormHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException { contentType = getMediaType(contentType); outputMessage.getHeaders().setContentType(contentType); Charset charset = contentType.getCharset(); Assert.notNull(charset, "No charset"); // should never occur final byte[] bytes = serializeForm(formData, charset).getBytes(charset); outputMessage.getHeaders().setContentLength(bytes.length); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream)); } else { StreamUtils.copy(bytes, outputMessage.getBody()); } }
Example #9
Source File: ResourceRegionHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (object instanceof ResourceRegion) { writeResourceRegion((ResourceRegion) object, outputMessage); } else { Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object; if (regions.size() == 1) { writeResourceRegion(regions.iterator().next(), outputMessage); } else { writeResourceRegionCollection((Collection<ResourceRegion>) object, outputMessage); } } }
Example #10
Source File: PropertiesHttpMessageConverter.java From SpringAll with MIT License | 6 votes |
@Override protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // 获取请求头 HttpHeaders headers = outputMessage.getHeaders(); // 获取 content-type MediaType contentType = headers.getContentType(); // 获取编码 Charset charset = null; if (contentType != null) { charset = contentType.getCharset(); } charset = charset == null ? Charset.forName("UTF-8") : charset; // 获取请求体 OutputStream body = outputMessage.getBody(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset); properties.store(outputStreamWriter, "Serialized by PropertiesHttpMessageConverter#writeInternal"); }
Example #11
Source File: ResourceRegionHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
protected void writeResourceRegion(ResourceRegion region, HttpOutputMessage outputMessage) throws IOException { Assert.notNull(region, "ResourceRegion must not be null"); HttpHeaders responseHeaders = outputMessage.getHeaders(); long start = region.getPosition(); long end = start + region.getCount() - 1; Long resourceLength = region.getResource().contentLength(); end = Math.min(end, resourceLength - 1); long rangeLength = end - start + 1; responseHeaders.add("Content-Range", "bytes " + start + '-' + end + '/' + resourceLength); responseHeaders.setContentLength(rangeLength); InputStream in = region.getResource().getInputStream(); try { StreamUtils.copyRange(in, outputMessage.getBody(), start, end); } finally { try { in.close(); } catch (IOException ex) { // ignore } } }
Example #12
Source File: BufferedImageHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
@Override public void write(final BufferedImage image, @Nullable final MediaType contentType, final HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { final MediaType selectedContentType = getContentType(contentType); outputMessage.getHeaders().setContentType(selectedContentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> writeInternal(image, selectedContentType, outputStream)); } else { writeInternal(image, selectedContentType, outputMessage.getBody()); } }
Example #13
Source File: AbstractGenericHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
/** * This implementation sets the default headers by calling {@link #addDefaultHeaders}, * and then calls {@link #writeInternal}. */ public final void write(final T t, @Nullable final Type type, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { final HttpHeaders headers = outputMessage.getHeaders(); addDefaultHeaders(headers, t, contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> writeInternal(t, type, new HttpOutputMessage() { @Override public OutputStream getBody() { return outputStream; } @Override public HttpHeaders getHeaders() { return headers; } })); } else { writeInternal(t, type, outputMessage); outputMessage.getBody().flush(); } }
Example #14
Source File: FastJsonHttpMessageConverterTest.java From swagger-dubbo with Apache License 2.0 | 5 votes |
@Test public void testSwagger() throws HttpMessageNotWritableException, IOException{ Json value = new Json("{\"swagger\":\"2.0\""); HttpOutputMessage outMessage = new MockHttpOutputMessage(){ @Override public HttpHeaders getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return httpHeaders; } }; new FastJsonHttpMessageConverter().write(value, null, outMessage); Assert.assertTrue((outMessage.getBody().toString().startsWith("{\"swagger\":\"2.0\""))); }
Example #15
Source File: HttpEntityMethodProcessorMockTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void shouldHandleReturnValue() throws Exception { String body = "Foo"; ResponseEntity<String> returnValue = new ResponseEntity<>(body, HttpStatus.OK); MediaType accepted = TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); initStringMessageConversion(accepted); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); verify(stringHttpMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); }
Example #16
Source File: SpringHttpMessageConverter.java From aaden-pay with Apache License 2.0 | 5 votes |
@Override protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException { if (writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset)); }
Example #17
Source File: FormHttpMessageConverter.java From spring-analysis-note with MIT License | 5 votes |
@Override @SuppressWarnings("unchecked") public void write(MultiValueMap<String, ?> map, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (!isMultipart(map, contentType)) { writeForm((MultiValueMap<String, Object>) map, contentType, outputMessage); } else { writeMultipart((MultiValueMap<String, Object>) map, outputMessage); } }
Example #18
Source File: ProtobufHttpMessageConverter.java From lams with GNU General Public License v2.0 | 5 votes |
@Override protected void writeInternal(Message message, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MediaType contentType = outputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = getDefaultContentType(message); } Charset charset = contentType.getCharset(); if (charset == null) { charset = DEFAULT_CHARSET; } if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset); TextFormat.print(message, outputStreamWriter); outputStreamWriter.flush(); } else if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) { JSON_FORMAT.print(message, outputMessage.getBody(), charset); } else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) { XML_FORMAT.print(message, outputMessage.getBody(), charset); } else if (MediaType.TEXT_HTML.isCompatibleWith(contentType)) { HTML_FORMAT.print(message, outputMessage.getBody(), charset); } else if (PROTOBUF.isCompatibleWith(contentType)) { setProtoHeader(outputMessage, message); FileCopyUtils.copy(message.toByteArray(), outputMessage.getBody()); } }
Example #19
Source File: ObjectToStringHttpMessageConverter.java From java-technology-stack with MIT License | 5 votes |
@Override protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException { String value = this.conversionService.convert(obj, String.class); if (value != null) { this.stringHttpMessageConverter.writeInternal(value, outputMessage); } }
Example #20
Source File: JsonMessageConverter.java From xiaoyaoji with GNU General Public License v3.0 | 5 votes |
@Override protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Result result; if(o instanceof Result){ result = (Result) o; }else{ result = new Result(true,o); } outputMessage.getHeaders().add("Content-Type","application/json;charset=utf-8"); super.writeInternal(result,outputMessage); }
Example #21
Source File: HttpEntityMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleReturnTypeResourceIllegalByteRange() throws Exception { ResponseEntity<Resource> returnValue = ResponseEntity .ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8))); servletRequest.addHeader("Range", "illegal"); given(resourceRegionMessageConverter.canWrite(any(), eq(null))).willReturn(true); given(resourceRegionMessageConverter.canWrite(any(), eq(APPLICATION_OCTET_STREAM))).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest); then(resourceRegionMessageConverter).should(never()).write( anyCollection(), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); assertEquals(416, servletResponse.getStatus()); }
Example #22
Source File: MyMessageConverter.java From springMvc4.x-project with Apache License 2.0 | 5 votes |
/** * ⑤ */ @Override protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { String out = "hello:" + obj.getId() + "-"+ obj.getName(); outputMessage.getBody().write(out.getBytes()); }
Example #23
Source File: HttpEntityMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void shouldHandleResource() throws Exception { ResponseEntity<Resource> returnValue = ResponseEntity .ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8))); given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true); given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL)); given(resourceMessageConverter.canWrite(ByteArrayResource.class, APPLICATION_OCTET_STREAM)).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest); then(resourceMessageConverter).should(times(1)).write( any(ByteArrayResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); assertEquals(200, servletResponse.getStatus()); }
Example #24
Source File: AbstractHttpMessageConverter.java From lams with GNU General Public License v2.0 | 5 votes |
/** * This implementation sets the default headers by calling {@link #addDefaultHeaders}, * and then calls {@link #writeInternal}. */ @Override public final void write(final T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { final HttpHeaders headers = outputMessage.getHeaders(); addDefaultHeaders(headers, t, contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() { @Override public void writeTo(final OutputStream outputStream) throws IOException { writeInternal(t, new HttpOutputMessage() { @Override public OutputStream getBody() throws IOException { return outputStream; } @Override public HttpHeaders getHeaders() { return headers; } }); } }); } else { writeInternal(t, outputMessage); outputMessage.getBody().flush(); } }
Example #25
Source File: StringHttpMessageConverter.java From lams with GNU General Public License v2.0 | 5 votes |
@Override protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException { if (this.writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); StreamUtils.copy(str, charset, outputMessage.getBody()); }
Example #26
Source File: StringHttpMessageConverter.java From java-technology-stack with MIT License | 5 votes |
@Override protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException { if (this.writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); StreamUtils.copy(str, charset, outputMessage.getBody()); }
Example #27
Source File: RequestResponseBodyMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleReturnTypeResource() throws Exception { Resource returnValue = new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)); given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true); given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL)); given(resourceMessageConverter.canWrite(ByteArrayResource.class, MediaType.APPLICATION_OCTET_STREAM)) .willReturn(true); processor.handleReturnValue(returnValue, returnTypeResource, mavContainer, webRequest); then(resourceMessageConverter).should(times(1)).write(any(ByteArrayResource.class), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); assertEquals(200, servletResponse.getStatus()); }
Example #28
Source File: RequestResponseBodyMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleReturnValueProduces() throws Exception { String body = "Foo"; servletRequest.addHeader("Accept", "text/*"); servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); given(stringMessageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true); processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); verify(stringMessageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); }
Example #29
Source File: HttpCharsetConvert.java From anyline with Apache License 2.0 | 5 votes |
@Override protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException { if (writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset)); }
Example #30
Source File: RequestResponseBodyMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleReturnValue() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); String body = "Foo"; given(stringMessageConverter.canWrite(String.class, null)).willReturn(true); given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(true); processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest); assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled()); verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); }