Java 类org.springframework.http.server.ServletServerHttpResponse 实例源码

项目:spring4-understanding    文件:HttpHeadersReturnValueHandler.java   
@Override
@SuppressWarnings("resource")
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    mavContainer.setRequestHandled(true);

    Assert.isInstanceOf(HttpHeaders.class, returnValue);
    HttpHeaders headers = (HttpHeaders) returnValue;

    if (!headers.isEmpty()) {
        HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
        ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
        outputMessage.getHeaders().putAll(headers);
        outputMessage.getBody(); // flush headers
    }
}
项目:spring4-understanding    文件:HttpEntityMethodProcessor.java   
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
    List<String> ifNoneMatch = inputMessage.getHeaders().getIfNoneMatch();
    long ifModifiedSince = inputMessage.getHeaders().getIfModifiedSince();
    String eTag = addEtagPadding(outputMessage.getHeaders().getETag());
    long lastModified = outputMessage.getHeaders().getLastModified();
    boolean notModified = false;

    if (!ifNoneMatch.isEmpty() && (inputMessage.getHeaders().containsKey(HttpHeaders.IF_UNMODIFIED_SINCE)
            || inputMessage.getHeaders().containsKey(HttpHeaders.IF_MATCH))) {
        // invalid conditional request, do not process
    }
    else if (lastModified != -1 && StringUtils.hasLength(eTag)) {
        notModified = isETagNotModified(ifNoneMatch, eTag) && isTimeStampNotModified(ifModifiedSince, lastModified);
    }
    else if (lastModified != -1) {
        notModified = isTimeStampNotModified(ifModifiedSince, lastModified);
    }
    else if (StringUtils.hasLength(eTag)) {
        notModified = isETagNotModified(ifNoneMatch, eTag);
    }
    return notModified;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpTunnelServerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.server = new HttpTunnelServer(this.serverConnection);
    given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
        @Override
        public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
            MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
            channel.setTimeout((Integer) invocation.getArguments()[0]);
            return channel;
        }
    });
    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
    this.serverChannel = new MockServerChannel();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DispatcherFilterTests.java   
@Test
public void handledByDispatcher() throws Exception {
    HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
    HttpServletResponse response = new MockHttpServletResponse();
    willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class),
            any(ServerHttpResponse.class));
    this.filter.doFilter(request, response, this.chain);
    verifyZeroInteractions(this.chain);
    verify(this.dispatcher).handle(this.serverRequestCaptor.capture(),
            this.serverResponseCaptor.capture());
    ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
    ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
    ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();
    ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse;
    assertThat(actualRequest.getServletRequest()).isEqualTo(request);
    assertThat(actualResponse.getServletResponse()).isEqualTo(response);
}
项目:spring-boot-concourse    文件:HttpTunnelServerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.server = new HttpTunnelServer(this.serverConnection);
    given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
        @Override
        public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
            MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
            channel.setTimeout((Integer) invocation.getArguments()[0]);
            return channel;
        }
    });
    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
    this.serverChannel = new MockServerChannel();
}
项目:spring-boot-concourse    文件:DispatcherFilterTests.java   
@Test
public void handledByDispatcher() throws Exception {
    HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
    HttpServletResponse response = new MockHttpServletResponse();
    willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class),
            any(ServerHttpResponse.class));
    this.filter.doFilter(request, response, this.chain);
    verifyZeroInteractions(this.chain);
    verify(this.dispatcher).handle(this.serverRequestCaptor.capture(),
            this.serverResponseCaptor.capture());
    ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
    ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
    ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();
    ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse;
    assertThat(actualRequest.getServletRequest()).isEqualTo(request);
    assertThat(actualResponse.getServletResponse()).isEqualTo(response);
}
项目:contestparser    文件:HttpTunnelServerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.server = new HttpTunnelServer(this.serverConnection);
    given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
        @Override
        public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
            MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
            channel.setTimeout((Integer) invocation.getArguments()[0]);
            return channel;
        }
    });
    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
    this.serverChannel = new MockServerChannel();
}
项目:contestparser    文件:DispatcherFilterTests.java   
@Test
public void handledByDispatcher() throws Exception {
    HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
    HttpServletResponse response = new MockHttpServletResponse();
    willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class),
            any(ServerHttpResponse.class));
    this.filter.doFilter(request, response, this.chain);
    verifyZeroInteractions(this.chain);
    verify(this.dispatcher).handle(this.serverRequestCaptor.capture(),
            this.serverResponseCaptor.capture());
    ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
    ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
    ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();
    ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse;
    assertThat(actualRequest.getServletRequest(), equalTo(request));
    assertThat(actualResponse.getServletResponse(), equalTo(response));
}
项目:springboot-shiro-cas-mybatis    文件:JsonViewUtils.java   
/**
 * Render model and view.
 *
 * @param model the model
 * @param response the response
 */
public static void render(final Object model, final HttpServletResponse response) {
    try {
        final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setPrettyPrint(true);
        final MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:springboot-shiro-cas-mybatis    文件:JsonViewUtils.java   
/**
 * Render model and view.
 *
 * @param model the model
 * @param response the response
 */
public static void render(final Object model, final HttpServletResponse response) {
    try {
        final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setPrettyPrint(true);
        final MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:cas-5.1.0    文件:JsonUtils.java   
/**
 * Render model and view.
 *
 * @param model the model
 * @param response the response
 */
public static void render(final Object model, final HttpServletResponse response) {
    try {
        final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setPrettyPrint(true);
        final MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
项目:cas-server-4.2.1    文件:JsonViewUtils.java   
/**
 * Render model and view.
 *
 * @param model the model
 * @param response the response
 */
public static void render(final Object model, final HttpServletResponse response) {
    try {
        final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setPrettyPrint(true);
        final MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:FastBootWeixin    文件:WxAsyncMessageReturnValueHandler.java   
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
                              ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    mavContainer.setRequestHandled(true);
    HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
    outputMessage.getBody();
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    WxRequest wxRequest = WxWebUtils.getWxRequestFromRequest(request);
    wxAsyncMessageTemplate.send(wxRequest, returnValue);
}
项目:oma-riista-web    文件:CustomAuthenticationFailureHandler.java   
@Override
public void onAuthenticationFailure(
        final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception)
                throws IOException {

    try (ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response)) {
        httpResponse.setStatusCode(HttpStatus.FORBIDDEN);

        messageConverter.write(createResponse(exception), MediaType.APPLICATION_JSON, httpResponse);
    }
}
项目:oauth4j    文件:JsonView.java   
/**
 * 以json视图返回
 *
 * @param model
 * @param response
 * @return
 */
public static ModelAndView render(Object model, HttpServletResponse response, boolean jsonSafe) {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    try {
        Object json = jsonSafe ? StringUtils.join(GlobalConstant.JSON_SAFE_PREFIX, model) : model;
        if(model instanceof ResultInfo) {
            json = ((ResultInfo) model).toJson();
        }
        jsonConverter.write(json, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
    } catch (IOException e) {
        log.error("Write response data [{}] as json view error!", model, e);
    }
    return null;
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
private ModelAndView handleResponseBody(Object returnValue, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());
    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }
    MediaType.sortByQualityValue(acceptedMediaTypes);
    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());
    Class<?> returnValueType = returnValue.getClass();
    if (this.messageConverters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : this.messageConverters) {
                if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                    messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                    return new ModelAndView();
                }
            }
        }
    }
    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " +
                acceptedMediaTypes);
    }
    return null;
}
项目:spring4-understanding    文件:AbstractMessageConverterMethodProcessor.java   
/**
 * Writes the given return value to the given web request. Delegates to
 * {@link #writeWithMessageConverters(Object, MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)}
 */
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType, NativeWebRequest webRequest)
        throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

    ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
    ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
    writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
项目:spring4-understanding    文件:HttpEntityMethodProcessor.java   
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    mavContainer.setRequestHandled(true);
    if (returnValue == null) {
        return;
    }

    ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
    ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

    Assert.isInstanceOf(HttpEntity.class, returnValue);
    HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

    HttpHeaders entityHeaders = responseEntity.getHeaders();
    if (!entityHeaders.isEmpty()) {
        outputMessage.getHeaders().putAll(entityHeaders);
    }

    Object body = responseEntity.getBody();
    if (responseEntity instanceof ResponseEntity) {
        outputMessage.setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
        if (HttpMethod.GET == inputMessage.getMethod() && isResourceNotModified(inputMessage, outputMessage)) {
            outputMessage.setStatusCode(HttpStatus.NOT_MODIFIED);
            // Ensure headers are flushed, no body should be written.
            outputMessage.flush();
            // Skip call to converters, as they may update the body.
            return;
        }
    }

    // Try even with null body. ResponseBodyAdvice could get involved.
    writeWithMessageConverters(body, returnType, inputMessage, outputMessage);

    // Ensure headers are flushed even if no body was written.
    outputMessage.flush();
}
项目:spring4-understanding    文件:StreamingResponseBodyReturnValueHandler.java   
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
    ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);

    if (ResponseEntity.class.isAssignableFrom(returnValue.getClass())) {
        ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
        outputMessage.setStatusCode(responseEntity.getStatusCode());
        outputMessage.getHeaders().putAll(responseEntity.getHeaders());

        returnValue = responseEntity.getBody();
        if (returnValue == null) {
            mavContainer.setRequestHandled(true);
            return;
        }
    }

    ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
    ShallowEtagHeaderFilter.disableContentCaching(request);

    Assert.isInstanceOf(StreamingResponseBody.class, returnValue);
    StreamingResponseBody streamingBody = (StreamingResponseBody) returnValue;

    Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
    WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
项目:spring4-understanding    文件:RequestResponseBodyAdviceChainTests.java   
@Before
public void setup() {
    this.body = "body";
    this.contentType = MediaType.TEXT_PLAIN;
    this.converterType = StringHttpMessageConverter.class;
    this.paramType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), 0);
    this.returnType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), -1);
    this.request = new ServletServerHttpRequest(new MockHttpServletRequest());
    this.response = new ServletServerHttpResponse(new MockHttpServletResponse());
}
项目:spring4-understanding    文件:RequestMappingHandlerAdapterTests.java   
@SuppressWarnings("unchecked")
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
        MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

    int status = ((ServletServerHttpResponse) response).getServletResponse().getStatus();
    response.setStatusCode(HttpStatus.OK);

    Map<String, Object> map = new LinkedHashMap<>();
    map.put("status", status);
    map.put("message", bodyContainer.getValue());
    bodyContainer.setValue(map);
}
项目:spring4-understanding    文件:JettyRequestUpgradeStrategy.java   
@Override
public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
        String selectedProtocol, List<WebSocketExtension> selectedExtensions, Principal user,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {

    Assert.isInstanceOf(ServletServerHttpRequest.class, request);
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

    Assert.isInstanceOf(ServletServerHttpResponse.class, response);
    HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();

    Assert.isTrue(this.factory.isUpgradeRequest(servletRequest, servletResponse), "Not a WebSocket handshake");

    JettyWebSocketSession session = new JettyWebSocketSession(attributes, user);
    JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(wsHandler, session);

    WebSocketHandlerContainer container =
            new WebSocketHandlerContainer(handlerAdapter, selectedProtocol, selectedExtensions);

    try {
        wsContainerHolder.set(container);
        this.factory.acceptWebSocket(servletRequest, servletResponse);
    }
    catch (IOException ex) {
        throw new HandshakeFailureException(
                "Response update failed during upgrade to WebSocket: " + request.getURI(), ex);
    }
    finally {
        wsContainerHolder.remove();
    }
}
项目:spring4-understanding    文件:SockJsHttpRequestHandler.java   
@Override
public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
    ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);

    try {
        this.sockJsService.handleRequest(request, response, getSockJsPath(servletRequest), this.webSocketHandler);
    }
    catch (Throwable ex) {
        throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), ex);
    }
}
项目:spring4-understanding    文件:SockJsServiceTests.java   
@Test  // SPR-11919
@SuppressWarnings("unchecked")
public void handleInfoGetWildflyNPE() throws Exception {
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ServletOutputStream ous = mock(ServletOutputStream.class);
    given(mockResponse.getHeaders(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).willThrow(NullPointerException.class);
    given(mockResponse.getOutputStream()).willReturn(ous);
    this.response = new ServletServerHttpResponse(mockResponse);

    handleRequest("GET", "/echo/info", HttpStatus.OK);

    verify(mockResponse, times(1)).getOutputStream();
}
项目:spring4-understanding    文件:HttpSockJsSessionTests.java   
@Before
public void setup() {

    super.setUp();

    this.frameFormat = new DefaultSockJsFrameFormat("%s");

    this.servletResponse = new MockHttpServletResponse();
    this.response = new ServletServerHttpResponse(this.servletResponse);

    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.request = new ServletServerHttpRequest(this.servletRequest);
}
项目:spring4-understanding    文件:DefaultCorsProcessor.java   
@Override
public boolean processRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (!CorsUtils.isCorsRequest(request)) {
        return true;
    }

    ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
    ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request);

    if (WebUtils.isSameOrigin(serverRequest)) {
        logger.debug("Skip CORS processing, request is a same-origin one");
        return true;
    }
    if (responseHasCors(serverResponse)) {
        logger.debug("Skip CORS processing, response already contains \"Access-Control-Allow-Origin\" header");
        return true;
    }

    boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
    if (config == null) {
        if (preFlightRequest) {
            rejectRequest(serverResponse);
            return false;
        }
        else {
            return true;
        }
    }

    return handleInternal(serverRequest, serverResponse, config, preFlightRequest);
}
项目:spring4-understanding    文件:ObjectToStringHttpMessageConverterTests.java   
@Before
public void setUp() {
    ConversionService conversionService = new DefaultConversionService();
    this.converter = new ObjectToStringHttpMessageConverter(conversionService);

    this.servletResponse = new MockHttpServletResponse();
    this.response = new ServletServerHttpResponse(this.servletResponse);
}
项目:everyone-java-blog    文件:JsonHandlerMethodReturnValueHandler.java   
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    mavContainer.setRequestHandled(true);
    HttpServletResponse httpServletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    httpServletResponse.setContentType(CONTENT_TYPE);
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse);
    JsonResponse jsonResponse = new JsonResponse(returnValue);
    outputMessage.getBody().write(StringUtils.toBytes(JsonUtils.toJson(jsonResponse)));
    outputMessage.getBody().flush();
}
项目:commons-rules    文件:RestExceptionHandler.java   
@SuppressWarnings({ "rawtypes", "unchecked", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest) throws HttpMessageNotWritableException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.messageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and " + acceptedMediaTypes);
    }
    return null;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DispatcherFilter.java   
private void doFilter(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    ServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
    ServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
    if (!this.dispatcher.handle(serverRequest, serverResponse)) {
        chain.doFilter(request, response);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpRestartServerTests.java   
@Test
public void sendClassLoaderFiles() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ClassLoaderFiles files = new ClassLoaderFiles();
    files.addFile("name", new ClassLoaderFile(Kind.ADDED, new byte[0]));
    byte[] bytes = serialize(files);
    request.setContent(bytes);
    this.server.handle(new ServletServerHttpRequest(request),
            new ServletServerHttpResponse(response));
    verify(this.delegate).updateAndRestart(this.filesCaptor.capture());
    assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull();
    assertThat(response.getStatus()).isEqualTo(200);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpRestartServerTests.java   
@Test
public void sendNoContent() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    this.server.handle(new ServletServerHttpRequest(request),
            new ServletServerHttpResponse(response));
    verifyZeroInteractions(this.delegate);
    assertThat(response.getStatus()).isEqualTo(500);

}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpRestartServerTests.java   
@Test
public void sendBadData() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setContent(new byte[] { 0, 0, 0 });
    this.server.handle(new ServletServerHttpRequest(request),
            new ServletServerHttpResponse(response));
    verifyZeroInteractions(this.delegate);
    assertThat(response.getStatus()).isEqualTo(500);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpTunnelPayloadTests.java   
@Test
public void assignTo() throws Exception {
    ByteBuffer data = ByteBuffer.wrap("hello".getBytes());
    HttpTunnelPayload payload = new HttpTunnelPayload(2, data);
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    HttpOutputMessage response = new ServletServerHttpResponse(servletResponse);
    payload.assignTo(response);
    assertThat(servletResponse.getHeader("x-seq")).isEqualTo("2");
    assertThat(servletResponse.getContentAsString()).isEqualTo("hello");
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpStatusHandlerTests.java   
@Before
public void setup() {
    this.servletRequest = new MockHttpServletRequest();
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DispatcherTests.java   
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.serverRequest = new ServletServerHttpRequest(this.request);
    this.serverResponse = new ServletServerHttpResponse(this.response);
}
项目:meazza    文件:JsonViewHelper.java   
/**
 * 将指定的 model 以 JSON 格式输出到 HTTP 响应中。
 * 
 * @param model
 *            数据对象
 * @param request
 *            Spring ServletWebRequest
 * @param mediaType
 *            输出响应的 MIME 类型
 * @return 返回 null
 */
public static ModelAndView render(Object model, ServletWebRequest request, MediaType mediaType) {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();

    try {
        jsonConverter.write(model, mediaType, new ServletServerHttpResponse(request.getResponse()));
    } catch (HttpMessageNotWritableException | IOException e) {
        logger.error("Render jsonView error", e);
    }

    return null;
}
项目:cas4.1.9    文件:JsonViewUtils.java   
/**
 * Render model and view.
 *
 * @param model the model
 * @param response the response
 */
public static void render(final Object model, final HttpServletResponse response) {
    try {
        final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setPrettyPrint(true);
        final MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:spring-boot-concourse    文件:DispatcherFilter.java   
private void doFilter(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    ServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
    ServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
    if (!this.dispatcher.handle(serverRequest, serverResponse)) {
        chain.doFilter(request, response);
    }
}
项目:spring-boot-concourse    文件:HttpRestartServerTests.java   
@Test
public void sendClassLoaderFiles() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ClassLoaderFiles files = new ClassLoaderFiles();
    files.addFile("name", new ClassLoaderFile(Kind.ADDED, new byte[0]));
    byte[] bytes = serialize(files);
    request.setContent(bytes);
    this.server.handle(new ServletServerHttpRequest(request),
            new ServletServerHttpResponse(response));
    verify(this.delegate).updateAndRestart(this.filesCaptor.capture());
    assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull();
    assertThat(response.getStatus()).isEqualTo(200);
}