org.springframework.http.converter.HttpMessageNotWritableException Java Examples
The following examples show how to use
org.springframework.http.converter.HttpMessageNotWritableException.
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: GsonHttpMessageConverter.java From lams with GNU General Public License v2.0 | 6 votes |
@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 #2
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 #3
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 #4
Source File: MarshallingHttpMessageConverterTests.java From java-technology-stack with MIT License | 6 votes |
@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 #5
Source File: FastJsonResponseUtil.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
@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 #6
Source File: AbstractJsonHttpMessageConverter.java From spring-analysis-note 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 #7
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 #8
Source File: SourceHttpMessageConverter.java From spring-analysis-note with MIT License | 5 votes |
@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 #9
Source File: ServletInvocableHandlerMethodTests.java From java-technology-stack with MIT License | 5 votes |
@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 #10
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 #11
Source File: ProtobufHttpMessageConverter.java From java-technology-stack with MIT License | 5 votes |
@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 #12
Source File: SourceHttpMessageConverter.java From java-technology-stack with MIT License | 5 votes |
@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 #13
Source File: StringOrJsonHttpMessageConverter.java From summerframework with Apache License 2.0 | 5 votes |
@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 #14
Source File: InputStreamMessageConverter.java From n2o-framework with Apache License 2.0 | 5 votes |
@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 #15
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 #16
Source File: FastJsonHttpMessageConverter.java From mcg-helper with Apache License 2.0 | 5 votes |
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 #17
Source File: FastJsonHttpMessageConverter.java From mcg-helper with Apache License 2.0 | 5 votes |
@Override protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.writeInternal(obj, outputMessage); }
Example #18
Source File: JsonMergePatchHttpMessageConverter.java From http-patch-spring with MIT License | 5 votes |
@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 #19
Source File: CustomAccessDeniedHandler.java From oauth2-server with MIT License | 5 votes |
@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); } }
Example #20
Source File: HttpConverterXml.java From mercury with Apache License 2.0 | 5 votes |
@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)); } }
Example #21
Source File: HttpConverterHtml.java From mercury with Apache License 2.0 | 5 votes |
@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>")); } }
Example #22
Source File: HttpConverterText.java From mercury with Apache License 2.0 | 5 votes |
@Override public void write(Object o, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException, IOException { outputMessage.getHeaders().setContentType(TEXT_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(mapper.writeValueAsBytes(o)); } }
Example #23
Source File: SeezoonFastJsonHttpMessageConverter.java From seezoon-framework-all with Apache License 2.0 | 5 votes |
@Override protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (null != obj && obj instanceof ResponeModel) { ResponeModel responeModel = (ResponeModel) obj; String responeCode = responeModel.getResponeCode(); String msg = messageSource.getMessage(responeCode, responeModel.getParams(), responeModel.getResponeMsg(), this.getLocale()); responeModel.setResponeMsg(msg); } super.writeInternal(obj, outputMessage); }
Example #24
Source File: GlobalExceptionHandler.java From ywh-frame with GNU General Public License v3.0 | 5 votes |
/** * 500错误拦截 * @param ex 异常信息 * @return 返回前端异常信息 */ @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class}) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result request500(RuntimeException ex){ log.error("错误详情:" + ex.getMessage(),ex); return Result.errorJson(BaseEnum.INTERNAL_SERVER_ERROR.getMsg(),BaseEnum.INTERNAL_SERVER_ERROR.getIndex()); }
Example #25
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 #26
Source File: AbstractMessageConverterMethodProcessor.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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 #27
Source File: RequestResponseBodyMethodProcessor.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void handleReturnValue(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 #28
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 #29
Source File: SourceHttpMessageConverter.java From lams with GNU General Public License v2.0 | 5 votes |
@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 #30
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()); }