类org.springframework.http.converter.HttpMessageNotWritableException源码实例Demo

下面列出了怎么用org.springframework.http.converter.HttpMessageNotWritableException的API类实例代码及写法,或者点击链接到github查看源代码。

@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();
}
 
@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();
}
 
@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);
	}
}
 
源代码4 项目: stategen   文件: FastJsonResponseUtil.java
@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);
    }
}
 
源代码5 项目: oauth2-server   文件: CustomAccessDeniedHandler.java
@Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response, AccessDeniedException e) throws IOException {
        //服务器地址
        String toUrl = ClientIpUtil.getFullRequestUrl(request);
        boolean isAjax = "XMLHttpRequest".equals(request
            .getHeader("X-Requested-With")) || "apiLogin".equals(request
            .getHeader("api-login"));
        if (isAjax) {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try {
                ResponseResult<Object> responseMessage = new ResponseResult<>();
                responseMessage.setStatus(GlobalConstant.ERROR_DENIED);
                responseMessage.setMessage(toUrl);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(),
                    JsonEncoding.UTF8);
                objectMapper.writeValue(jsonGenerator, responseMessage);
            } catch (Exception ex) {
                throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
            }
        } else {
///            response.sendRedirect(accessDeniedUrl + "?toUrl=" + toUrl);
            response.sendRedirect(accessDeniedUrl);
        }
    }
 
源代码6 项目: mercury   文件: HttpConverterXml.java
@Override
@SuppressWarnings("unchecked")
public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException, IOException {
    outputMessage.getHeaders().setContentType(XML);
    // this may be too late to validate because Spring RestController has already got the object
    SimpleObjectMapper mapper = SimpleMapper.getInstance().getWhiteListMapper(o.getClass().getTypeName());
    OutputStream out = outputMessage.getBody();
    if (o instanceof String) {
        out.write(util.getUTF((String) o));
    } else if (o instanceof byte[]) {
        out.write((byte[]) o);
    } else {
        Map<String, Object> map;
        if (o instanceof List) {
            map = new HashMap<>();
            map.put("item", mapper.readValue(o, List.class));
        } else if (o instanceof Map) {
            map = (Map<String, Object>) o;
        } else {
            map = mapper.readValue(o, Map.class);
        }
        String root = o.getClass().getSimpleName().toLowerCase();
        String result = map2xml.write(root, map);
        out.write(util.getUTF(result));
    }
}
 
源代码7 项目: mercury   文件: HttpConverterHtml.java
@Override
public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException, IOException {
    outputMessage.getHeaders().setContentType(HTML_CONTENT);
    // this may be too late to validate because Spring RestController has already got the object
    SimpleObjectMapper mapper = SimpleMapper.getInstance().getWhiteListMapper(o.getClass().getTypeName());
    OutputStream out = outputMessage.getBody();
    if (o instanceof String) {
        out.write(util.getUTF((String) o));
    } else if (o instanceof byte[]) {
        out.write((byte[]) o);
    } else {
        out.write(util.getUTF("<html><body><pre>\n"));
        out.write(mapper.writeValueAsBytes(o));
		out.write(util.getUTF("\n</pre></body></html>"));
    }
}
 
@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");
}
 
源代码9 项目: lams   文件: GsonHttpMessageConverter.java
@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);
	}
}
 
@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);
    }
}
 
@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);
    }
}
 
@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);
}
 
源代码13 项目: gemini   文件: EntityRecordListMessageConverter.java
@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);
}
 
源代码14 项目: gemini   文件: CountRequestMessageConverter.java
@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);
}
 
源代码15 项目: gemini   文件: CountRequestApiMessageConverter.java
@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);
}
 
/**
 * 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);
}
 
@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);
}
 
@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());
}
 
源代码19 项目: xiaoyaoji   文件: JsonMessageConverter.java
@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);
}
 
@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();
	}
}
 
@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);
	}
}
 
@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);
}
 
@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());
}
 
@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");
}
 
源代码25 项目: springMvc4.x-project   文件: MyMessageConverter.java
/**
 * ⑤
 */
@Override
protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	String out = "hello:" + obj.getId() + "-"+ obj.getName();
	outputMessage.getBody().write(out.getBytes());
}
 
@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();
	}
}
 
@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);
	}
}
 
@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);
}
 
@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();
}
 
源代码30 项目: springMvc4.x-project   文件: MyMessageConverter.java
/**
 * ⑤
 */
@Override
protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	String out = "hello:" + obj.getId() + "-"+ obj.getName();
	outputMessage.getBody().write(out.getBytes());
}
 
 类所在包
 同包方法