org.springframework.http.server.ServerHttpResponse源码实例Demo

类org.springframework.http.server.ServerHttpResponse源码实例Demo

下面列出了org.springframework.http.server.ServerHttpResponse 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: AbstractJsonpResponseBodyAdvice.java
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	for (String name : this.jsonpQueryParamNames) {
		String value = servletRequest.getParameter(name);
		if (value != null) {
			if (!isValidJsonpQueryParam(value)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Ignoring invalid jsonp parameter value: " + value);
				}
				continue;
			}
			MediaType contentTypeToUse = getContentType(contentType, request, response);
			response.getHeaders().setContentType(contentTypeToUse);
			bodyContainer.setJsonpFunction(value);
			break;
		}
	}
}
 
源代码2 项目: spring-tutorial   文件: HandShake.java
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
	Map<String, Object> attributes) throws Exception {
	System.out.println("Websocket:用户[ID:"
		+ ((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("uid")
		+ "]已经建立连接");
	if (request instanceof ServletServerHttpRequest) {
		ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
		HttpSession session = servletRequest.getServletRequest().getSession(false);
		// 标记用户
		Long uid = (Long) session.getAttribute("uid");
		if (uid != null) {
			attributes.put("uid", uid);
		} else {
			return false;
		}
	}
	return true;
}
 
public boolean applyBeforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
		Map<String, Object> attributes) throws Exception {

	for (int i = 0; i < this.interceptors.size(); i++) {
		HandshakeInterceptor interceptor = this.interceptors.get(i);
		if (!interceptor.beforeHandshake(request, response, this.wsHandler, attributes)) {
			if (logger.isDebugEnabled()) {
				logger.debug(interceptor + " returns false from beforeHandshake - precluding handshake");
			}
			applyAfterHandshake(request, response, null);
			return false;
		}
		this.interceptorIndex = i;
	}
	return true;
}
 
@Override
public boolean beforeHandshake(final ServerHttpRequest request, final ServerHttpResponse response, final WebSocketHandler wsHandler, final Map<String, Object> attributes) throws Exception
{
	// UserSession.getCurrent().assertLoggedIn();
	// return true;

	final UserSession userSession = UserSession.getCurrentOrNull();
	if (userSession == null)
	{
		logger.warn("Websocket connection not allowed (missing userSession)");
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		return false;
	}

	if (!userSession.isLoggedIn())
	{
		logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession);
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		return false;
	}

	return true;
}
 
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
		throws IOException {

	if (WebUtils.isSameOrigin(request)) {
		return true;
	}

	if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
		if (logger.isWarnEnabled()) {
			logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
		}
		response.setStatusCode(HttpStatus.FORBIDDEN);
		return false;
	}

	return true;
}
 
/**
 * Handle all requests, except the first one, to receive messages on a SockJS
 * HTTP transport based session.
 * <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
 * after writing any buffered message frames (or the next one). Streaming-based
 * transports ("xhr_streaming", "eventsource", and "htmlfile") leave the
 * response open longer for further streaming of message frames but will also
 * close it eventually after some amount of data has been sent.
 * @param request the current request
 * @param response the current response
 * @param frameFormat the transport-specific SocksJS frame format to use
 */
public void handleSuccessiveRequest(ServerHttpRequest request, ServerHttpResponse response,
		SockJsFrameFormat frameFormat) throws SockJsException {

	synchronized (this.responseLock) {
		try {
			if (isClosed()) {
				response.getBody().write(SockJsFrame.closeFrameGoAway().getContentBytes());
				return;
			}
			this.response = response;
			this.frameFormat = frameFormat;
			ServerHttpAsyncRequestControl control = request.getAsyncRequestControl(response);
			this.asyncRequestControl = control;
			control.start(-1);
			disableShallowEtagHeaderFilter(request);
			handleRequestInternal(request, response, false);
			this.readyToSend = isActive();
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to handle SockJS receive request", getId(), ex);
		}
	}
}
 
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    ResponseResult responseResultAnn = (ResponseResult) RequestContextHolderUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);

    Class<? extends Result> resultClazz = responseResultAnn.value();

    if (resultClazz.isAssignableFrom(PlatformResult.class)) {
        if (body instanceof DefaultErrorResult) {
            DefaultErrorResult defaultErrorResult = (DefaultErrorResult) body;
            return PlatformResult.builder()
                    .code(defaultErrorResult.getCode())
                    .message(defaultErrorResult.getMessage())
                    .data(defaultErrorResult.getErrors())
                    .build();
        }

        return PlatformResult.success(body);
    }

    return body;
}
 
源代码8 项目: mPaaS   文件: ResponseEntityAdvice.java
@Override
public Object beforeBodyWrite(Object o,
                              MethodParameter methodParameter,
                              MediaType mediaType,
                              Class<? extends HttpMessageConverter<?>> aClass,
                              ServerHttpRequest serverHttpRequest,
                              ServerHttpResponse HttpServletResponse) {
    if (serverHttpRequest instanceof ServletServerHttpRequest) {
        javax.servlet.http.HttpServletResponse response = ((ServletServerHttpResponse) HttpServletResponse).getServletResponse();
        if (hasError(HttpStatus.valueOf(response.getStatus()))) {
            return new Response(false, "status." + response.getStatus(), null, o);
        } else {
            return Response.ok(o);
        }
    }
    return o;
}
 
@SuppressWarnings("unchecked")
@Override
public String beforeBodyWrite(String body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return body + "-TargetedControllerAdvice";
}
 
源代码10 项目: spring-boot-rest-api-helpers   文件: BodyAdvice.java
@Override
@SuppressWarnings("unchecked")
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

    if (body == null) {
        throw new NotFoundException("Resource was not found!");
    }
    if (isArray(body)) {
        return new Wrapper(Arrays.asList(body));
    }
    if (body instanceof Iterable && !(body instanceof Page)) {
        return new Wrapper((Iterable)body);
    }
    return body;
}
 
源代码11 项目: jt808-server   文件: WebSocketInterceptor.java
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
    if (request instanceof ServletServerHttpRequest) {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        HttpSession session = servletRequest.getSession();
        Integer id = (Integer) session.getAttribute(SessionKey.USER_ID);
        if (id != null) {
            webSocketMessageHandler.closeSession(id);
            attributes.put(SessionKey.USER_ID, id);
            return true;
        }
    }
    return false;
}
 
源代码12 项目: we-cmdb   文件: InhouseCmdbResponseResultProcess.java
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (body instanceof CustomResponseDto) {
        return body;
    } else {
        if (body == null) {
            body = SUCCESS;
        }
        return InhouseCmdbResponse.okayWithData(body);
    }
}
 
源代码13 项目: MyBlog   文件: MyHandshakeInterceptor.java
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    //未登录则不建立连接
    if (!subject.isAuthenticated() && !subject.isRemembered()) {
        return false;
    }
    String username = (String) SecurityUtils.getSubject().getPrincipal();
    if (StringUtils.isBlank(username)) {
        //用户名为空则不建立连接
        return false;
    }
    attributes.put("username", username);
    return true;
}
 
@Override
@Nullable
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType contentType,
		Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return processBody(body, returnType, contentType, converterType, request, response);
}
 
@Override
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
		WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException {

	Assert.notNull(wsSession, "No session");
	AbstractHttpSockJsSession sockJsSession = (AbstractHttpSockJsSession) wsSession;

	handleRequestInternal(request, response, wsHandler, sockJsSession);
}
 
源代码16 项目: tracee   文件: TraceeResponseBodyAdvice.java
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
															Class<? extends HttpMessageConverter<?>> selectedConverterType,
															ServerHttpRequest springHttpRequest, ServerHttpResponse springHttpResponse) {
	if (springHttpRequest instanceof ServletServerHttpRequest && springHttpResponse instanceof ServletServerHttpResponse) {
		final HttpServletRequest request = ((ServletServerHttpRequest) springHttpRequest).getServletRequest();
		final HttpServletResponse response = ((ServletServerHttpResponse) springHttpResponse).getServletResponse();

		interceptor.afterCompletion(request, response, null, null);
	}
	return body;
}
 
private void handleReadError(ServerHttpResponse response, String error, String sessionId) {
	try {
		response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		response.getBody().write(error.getBytes(StandardCharsets.UTF_8));
	}
	catch (IOException ex) {
		throw new SockJsException("Failed to send error: " + error, sessionId, ex);
	}
}
 
private void handleReadError(ServerHttpResponse response, String error, String sessionId) {
	try {
		response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		response.getBody().write(error.getBytes(UTF8_CHARSET));
	}
	catch (IOException ex) {
		throw new SockJsException("Failed to send error: " + error, sessionId, ex);
	}
}
 
源代码19 项目: lams   文件: DefaultCorsProcessor.java
private boolean responseHasCors(ServerHttpResponse response) {
	try {
		return (response.getHeaders().getAccessControlAllowOrigin() != null);
	}
	catch (NullPointerException npe) {
		// SPR-11919 and https://issues.jboss.org/browse/WFLY-3474
		return false;
	}
}
 
@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 (returnValue instanceof ResponseEntity) {
		ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
		response.setStatus(responseEntity.getStatusCodeValue());
		outputMessage.getHeaders().putAll(responseEntity.getHeaders());
		returnValue = responseEntity.getBody();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

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

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

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
@Override
protected void writeFrameInternal(SockJsFrame frame) throws IOException {
	if (isActive()) {
		SockJsFrameFormat frameFormat = this.frameFormat;
		ServerHttpResponse response = this.response;
		if (frameFormat != null && response != null) {
			String formattedFrame = frameFormat.format(frame);
			if (logger.isTraceEnabled()) {
				logger.trace("Writing to HTTP response: " + formattedFrame);
			}
			response.getBody().write(formattedFrame.getBytes(SockJsFrame.CHARSET));
			response.flush();
		}
	}
}
 
/**
 * Handle the first request for receiving messages on a SockJS HTTP transport
 * based session.
 * <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
 * after writing the open frame. Streaming-based transports ("xhr_streaming",
 * "eventsource", and "htmlfile") leave the response open longer for further
 * streaming of message frames but will also close it eventually after some
 * amount of data has been sent.
 * @param request the current request
 * @param response the current response
 * @param frameFormat the transport-specific SocksJS frame format to use
 */
public void handleInitialRequest(ServerHttpRequest request, ServerHttpResponse response,
		SockJsFrameFormat frameFormat) throws SockJsException {

	this.uri = request.getURI();
	this.handshakeHeaders = request.getHeaders();
	this.principal = request.getPrincipal();
	this.localAddress = request.getLocalAddress();
	this.remoteAddress = request.getRemoteAddress();

	synchronized (this.responseLock) {
		try {
			this.response = response;
			this.frameFormat = frameFormat;
			this.asyncRequestControl = request.getAsyncRequestControl(response);
			this.asyncRequestControl.start(-1);

			disableShallowEtagHeaderFilter(request);

			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();

			handleRequestInternal(request, response, true);

			// Request might have been reset (e.g. polling sessions do after writing)
			this.readyToSend = isActive();
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to open session", getId(), ex);
		}
	}
}
 
@Override
public String beforeBodyWrite(String body, MethodParameter returnType,
                              MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                              ServerHttpRequest request, ServerHttpResponse response) {
    if (!(request instanceof ServletServerHttpRequest) || StringUtils.isEmpty(body)) {
        return null;
    }
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    WxRequest wxRequest = WxWebUtils.getWxRequestFromRequest(servletRequest);
    WxUserMessage text = WxMessage.Text.builder().content(body).build();
    return parseXml(wxMessageProcessor.process(new WxRequestMessageParameter(wxRequest), text));
}
 
protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
	if (logger.isErrorEnabled()) {
		logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection());
	}
	response.setStatusCode(HttpStatus.BAD_REQUEST);
	response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(StandardCharsets.UTF_8));
}
 
protected void handleWebSocketVersionNotSupported(ServerHttpRequest request, ServerHttpResponse response) {
	if (logger.isErrorEnabled()) {
		String version = request.getHeaders().getFirst("Sec-WebSocket-Version");
		logger.error("Handshake failed due to unsupported WebSocket version: " + version +
				". Supported versions: " + Arrays.toString(getSupportedVersions()));
	}
	response.setStatusCode(HttpStatus.UPGRADE_REQUIRED);
	response.getHeaders().set(WebSocketHttpHeaders.SEC_WEBSOCKET_VERSION,
			StringUtils.arrayToCommaDelimitedString(getSupportedVersions()));
}
 
@Override
@Nullable
public final Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	if (body == null) {
		return null;
	}
	MappingJacksonValue container = getOrCreateContainer(body);
	beforeBodyWriteInternal(container, contentType, returnType, request, response);
	return container;
}
 
源代码27 项目: java-technology-stack   文件: SseEmitter.java
@Override
protected void extendResponse(ServerHttpResponse outputMessage) {
	super.extendResponse(outputMessage);

	HttpHeaders headers = outputMessage.getHeaders();
	if (headers.getContentType() == null) {
		headers.setContentType(UTF8_TEXT_EVENTSTREAM);
	}
}
 
public void applyAfterHandshake(ServerHttpRequest request, ServerHttpResponse response, Exception failure) {
	for (int i = this.interceptorIndex; i >= 0; i--) {
		HandshakeInterceptor interceptor = this.interceptors.get(i);
		try {
			interceptor.afterHandshake(request, response, this.wsHandler, failure);
		}
		catch (Throwable ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(interceptor + " threw exception in afterHandshake: " + ex);
			}
		}
	}
}
 
@Override
protected void writeFrameInternal(SockJsFrame frame) throws IOException {
	if (isActive()) {
		SockJsFrameFormat frameFormat = this.frameFormat;
		ServerHttpResponse response = this.response;
		if (frameFormat != null && response != null) {
			String formattedFrame = frameFormat.format(frame);
			if (logger.isTraceEnabled()) {
				logger.trace("Writing to HTTP response: " + formattedFrame);
			}
			response.getBody().write(formattedFrame.getBytes(SockJsFrame.CHARSET));
			response.flush();
		}
	}
}
 
@Override
protected void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, String selectedProtocol,
                               List<Extension> selectedExtensions, Endpoint endpoint) throws HandshakeFailureException {
    HttpServletRequest servletRequest = getHttpServletRequest(request);
    ServletHttpServletRequest httpServletRequest = ServletUtil.unWrapper(servletRequest);
    if(httpServletRequest == null) {
        throw new HandshakeFailureException(
                "Servlet request failed to upgrade to WebSocket: " + servletRequest.getRequestURL());
    }

    WebSocketServerContainer serverContainer = getContainer(servletRequest);
    Principal principal = request.getPrincipal();
    Map<String, String> pathParams = new LinkedHashMap<>(3);

    ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(servletRequest.getRequestURI(), endpoint);
    endpointConfig.setSubprotocols(Arrays.asList(WebSocketServerHandshaker.SUB_PROTOCOL_WILDCARD,selectedProtocol));
    if(selectedExtensions != null) {
        endpointConfig.setExtensions(selectedExtensions);
    }

    try {
        handshakeToWebsocket(httpServletRequest, selectedProtocol, maxFramePayloadLength, principal,
                selectedExtensions, pathParams, endpoint,
                endpointConfig, serverContainer);
    } catch (Exception e) {
        throw new HandshakeFailureException(
                "Servlet request failed to upgrade to WebSocket: " + servletRequest.getRequestURL(), e);
    }
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法