Java Code Examples for org.springframework.http.converter.HttpMessageNotWritableException

The following examples show how to use org.springframework.http.converter.HttpMessageNotWritableException. These examples are extracted from open source projects. 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
@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
@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 3
@Test
public void writeWithMarshallingFailureException() throws Exception {
	String body = "<root>Hello World</root>";
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	MarshallingFailureException ex = new MarshallingFailureException("forced");

	Marshaller marshaller = mock(Marshaller.class);
	willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class));

	try {
		MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
		converter.write(body, null, outputMessage);
		fail("HttpMessageNotWritableException should be thrown");
	}
	catch (HttpMessageNotWritableException e) {
		assertTrue("Invalid exception hierarchy", e.getCause() == ex);
	}
}
 
Example 4
@SuppressWarnings("resource")
public static void writeResponse(Object result) {
    HttpServletResponse httpServletResponse = ServletContextUtil.getHttpServletResponse();
    ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(httpServletResponse);
    HttpHeaders headers = servletServerHttpResponse.getHeaders();
    
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
    httpServletResponse.setStatus(HttpStatus.OK.value());
    try {
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        FASTJSON_HTTP_MESSAGE_CONVERTOR.write(result, headers.getContentType(), new HttpOutputMessage() {
            @Override
            public OutputStream getBody() throws IOException {
                return outputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return headers;
            }
        });
    } catch (HttpMessageNotWritableException | IOException e) {
        logger.error("internal error", e);
    }
}
 
Example 5
Source Project: SpringAll   Source File: PropertiesHttpMessageConverter.java    License: MIT License 6 votes vote down vote up
@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 6
@Override
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	Charset charset = getCharset(outputMessage.getHeaders());
	OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset);
	try {
		if (this.jsonPrefix != null) {
			writer.append(this.jsonPrefix);
		}
		if (type != null) {
			this.gson.toJson(o, type, writer);
		}
		else {
			this.gson.toJson(o, writer);
		}
		writer.close();
	}
	catch (JsonIOException ex) {
		throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
	}
}
 
Example 7
Source Project: http-patch-spring   Source File: JsonPatchHttpMessageConverter.java    License: MIT License 5 votes vote down vote up
@Override
protected void writeInternal(JsonPatch jsonPatch, HttpOutputMessage outputMessage)
        throws HttpMessageNotWritableException {

    try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
        writer.write(jsonPatch.toJsonArray());
    } catch (Exception e) {
        throw new HttpMessageNotWritableException(e.getMessage(), e);
    }
}
 
Example 8
@Override
protected void writeInternal(JsonMergePatch jsonMergePatch, HttpOutputMessage outputMessage)
        throws HttpMessageNotWritableException {

    try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
        writer.write(jsonMergePatch.toJsonValue());
    } catch (Exception e) {
        throw new HttpMessageNotWritableException(e.getMessage(), e);
    }
}
 
Example 9
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    GeminiWrappers.EntityRecordListApiType record = GeminiWrappers.EntityRecordListApiType.class.cast(object);
    GeminiWrappers.EntityRecordsList entityRecordList = record.getEntityRecordList(); // unwrap

    Map<String, Object> responseBody = new HashMap<>();
    responseBody.put("meta", getMeta(entityRecordList));
    responseBody.put("data", getData(entityRecordList));
    super.writeInternal(responseBody, type, outputMessage);
}
 
Example 10
Source Project: gemini   Source File: EntityRecordListMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    GeminiWrappers.EntityRecordsList recordsWrapper = GeminiWrappers.EntityRecordsList.class.cast(object);
    Collection<EntityRecord> records = recordsWrapper.getRecords();
    List<Object> listOfFields = new ArrayList<>(records.size());
    for (EntityRecord record : records) {
        listOfFields.add(RecordConverters.fieldsToJSONMap(record));
    }
    super.writeInternal(listOfFields, type, outputMessage);
}
 
Example 11
Source Project: gemini   Source File: CountRequestMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    GeminiWrappers.CountRequest req = GeminiWrappers.CountRequest.class.cast(object);
    Map<String, Object> res = new HashMap<>();
    res.put("count", req.getResult());
    super.writeInternal(res, type, outputMessage);
}
 
Example 12
Source Project: gemini   Source File: CountRequestApiMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    GeminiWrappers.CountRequestApiType record = GeminiWrappers.CountRequestApiType.class.cast(object);
    GeminiWrappers.CountRequest countRequest = record.getCountRequest();// unwrap

    Map<String, Object> responseBody = new HashMap<>();
    responseBody.put("meta", getMeta(countRequest));
    responseBody.put("data", getData(countRequest));
    super.writeInternal(responseBody, type, outputMessage);
}
 
Example 13
/**
 * Writes the given return value to the given web request. Delegates to
 * {@link #writeWithMessageConverters(Object, MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)}
 */
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
	writeWithMessageConverters(value, returnType, inputMessage, outputMessage);
}
 
Example 14
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	mavContainer.setRequestHandled(true);
	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	// Try even with null return value. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example 15
@Test
public void handleHttpMessageNotWritable() {
	HttpMessageNotWritableException ex = new HttpMessageNotWritableException("foo");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 500, response.getStatus());
}
 
Example 16
@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 17
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
Example 18
Source Project: spring-analysis-note   Source File: SourceHttpMessageConverter.java    License: MIT License 5 votes vote down vote up
@Override
protected void writeInternal(T t, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	try {
		Result result = new StreamResult(outputMessage.getBody());
		transform(t, result);
	}
	catch (TransformerException ex) {
		throw new HttpMessageNotWritableException("Could not transform [" + t + "] to output message", ex);
	}
}
 
Example 19
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	mavContainer.setRequestHandled(true);
	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	// Try even with null return value. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example 20
@Test
public void handleHttpMessageNotWritable() {
	HttpMessageNotWritableException ex = new HttpMessageNotWritableException("foo");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 500, response.getStatus());
}
 
Example 21
@Test(expected = HttpMessageNotWritableException.class)
public void invokeAndHandle_Exception() throws Exception {
	this.returnValueHandlers.addHandler(new ExceptionRaisingReturnValueHandler());

	ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "handle");
	handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);
	fail("Expected exception");
}
 
Example 22
Source Project: springMvc4.x-project   Source File: MyMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * ⑤
 */
@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
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
Example 24
Source Project: java-technology-stack   Source File: SourceHttpMessageConverter.java    License: MIT License 5 votes vote down vote up
@Override
protected void writeInternal(T t, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	try {
		Result result = new StreamResult(outputMessage.getBody());
		transform(t, result);
	}
	catch (TransformerException ex) {
		throw new HttpMessageNotWritableException("Could not transform [" + t + "] to output message", ex);
	}
}
 
Example 25
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    if(null!=object&& object instanceof String){
        outputMessage.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        stringHttpMessageConverter.write(object==null?null:(String)object, MediaType.TEXT_PLAIN,outputMessage);
        return ;
    }
    super.writeInternal(object, type, outputMessage);
}
 
Example 26
Source Project: n2o-framework   Source File: InputStreamMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(DataInputStream in, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    HttpHeaders httpHeaders = outputMessage.getHeaders();
    String subtype = httpHeaders.getContentType().getSubtype();
    logger.debug("Trying write DataInputStream into servlet OutputStream. Output subtype:{}", subtype);
    IOUtils.copy(in, outputMessage.getBody());
    in.close();
    outputMessage.getBody().close();
}
 
Example 27
Source Project: springMvc4.x-project   Source File: MyMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * ⑤
 */
@Override
protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	String out = "hello:" + obj.getId() + "-"+ obj.getName();
	outputMessage.getBody().write(out.getBytes());
}
 
Example 28
Source Project: mcg-helper   Source File: FastJsonHttpMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    HttpHeaders headers = outputMessage.getHeaders();
    String text = null;
    this.writeBefore(obj);
    if (!(obj instanceof JsonpResult)) {
        text = JSON.toJSONString(obj, //
                SerializeConfig.globalInstance, //
                filters, //
                dateFormat, //
                JSON.DEFAULT_GENERATE_FEATURE, //
                features);          
    } else {
        JsonpResult jsonp = (JsonpResult) obj;
        text = new StringBuilder(jsonp.getJsonpFunction())
                .append('(')
                .append(JSON.toJSONString(
                        jsonp.getValue(), //
                        SerializeConfig.globalInstance,
                        filters,
                        dateFormat,
                        JSON.DEFAULT_GENERATE_FEATURE,
                        features))
                .append(");").toString();
    }
    this.writeAfter(text);
    byte[] bytes = text.getBytes(charset);
    headers.setContentLength(bytes.length);
    OutputStream out = outputMessage.getBody();
    out.write(bytes);
    out.flush();
}
 
Example 29
Source Project: mcg-helper   Source File: FastJsonHttpMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object obj, Type type,
        HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {
    this.writeInternal(obj, outputMessage);

}
 
Example 30
Source Project: springMvc4.x-project   Source File: MyMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * ⑤
 */
@Override
protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	String out = "hello:" + obj.getId() + "-"+ obj.getName();
	outputMessage.getBody().write(out.getBytes());
}