org.springframework.http.server.ServerHttpResponse Java Examples

The following examples show how to use org.springframework.http.server.ServerHttpResponse. 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: HandshakeInterceptorChain.java    From java-technology-stack with MIT License 6 votes vote down vote up
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;
}
 
Example #2
Source File: AbstractSockJsService.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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;
}
 
Example #3
Source File: AbstractHttpSockJsSession.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example #4
Source File: WebSocketConfig.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: ResponseResultHandler.java    From spring-boot-api-project-seed with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: AbstractJsonpResponseBodyAdvice.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
		}
	}
}
 
Example #7
Source File: HandShake.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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;
}
 
Example #8
Source File: AbstractHandshakeHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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()));
}
 
Example #9
Source File: ResponseEntityAdvice.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: AbstractHttpReceivingTransportHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #11
Source File: AbstractHandshakeHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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));
}
 
Example #12
Source File: WxStringResponseBodyAdvice.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #13
Source File: AbstractMappingJacksonResponseBodyAdvice.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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;
}
 
Example #14
Source File: SseEmitter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void extendResponse(ServerHttpResponse outputMessage) {
	super.extendResponse(outputMessage);

	HttpHeaders headers = outputMessage.getHeaders();
	if (headers.getContentType() == null) {
		headers.setContentType(UTF8_TEXT_EVENTSTREAM);
	}
}
 
Example #15
Source File: AbstractHttpSockJsSession.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example #16
Source File: AbstractHttpSockJsSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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();
		}
	}
}
 
Example #17
Source File: RequestResponseBodyAdviceChainTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public String beforeBodyWrite(String body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return body + "-TargetedControllerAdvice";
}
 
Example #18
Source File: HandshakeInterceptorChain.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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);
			}
		}
	}
}
 
Example #19
Source File: AbstractHttpSockJsSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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();
		}
	}
}
 
Example #20
Source File: NettyRequestUpgradeStrategy.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #21
Source File: StreamingSockJsSession.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	byte[] prelude = getPrelude(request);
	Assert.notNull(prelude);
	response.getBody().write(prelude);
	response.flush();

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
	}
	flushCache();
}
 
Example #22
Source File: AbstractHttpReceivingTransportHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example #23
Source File: AbstractHttpReceivingTransportHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #24
Source File: SockJsServiceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void handleTransportRequest(ServerHttpRequest req, ServerHttpResponse res, WebSocketHandler handler,
		String sessionId, String transport) throws SockJsException {
	this.sessionId = sessionId;
	this.transport = transport;
	this.handler = handler;
}
 
Example #25
Source File: AbstractSockJsService.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
	if (request.getMethod() != HttpMethod.GET) {
		sendMethodNotAllowed(response, HttpMethod.GET);
		return;
	}

	String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl());
	byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
	StringBuilder builder = new StringBuilder("\"0");
	DigestUtils.appendMd5DigestAsHex(contentBytes, builder);
	builder.append('"');
	String etagValue = builder.toString();

	List<String> ifNoneMatch = request.getHeaders().getIfNoneMatch();
	if (!CollectionUtils.isEmpty(ifNoneMatch) && ifNoneMatch.get(0).equals(etagValue)) {
		response.setStatusCode(HttpStatus.NOT_MODIFIED);
		return;
	}

	response.getHeaders().setContentType(new MediaType("text", "html", StandardCharsets.UTF_8));
	response.getHeaders().setContentLength(contentBytes.length);

	// No cache in order to check every time if IFrame are authorized
	addNoCacheHeaders(response);
	response.getHeaders().setETag(etagValue);
	response.getBody().write(contentBytes);
}
 
Example #26
Source File: AbstractHttpSendingTransportHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
		WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException {

	AbstractHttpSockJsSession sockJsSession = (AbstractHttpSockJsSession) wsSession;

	// https://github.com/sockjs/sockjs-client/issues/130
	// sockJsSession.setAcceptedProtocol(protocol);

	// Set content type before writing
	response.getHeaders().setContentType(getContentType());

	handleRequestInternal(request, response, sockJsSession);
}
 
Example #27
Source File: ParamEncryptResponseBodyAdvice.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType,
		Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
	if (null != body) {

		boolean encode = false;
		if (methodParameter.getMethod()
				.isAnnotationPresent((Class<? extends Annotation>) SecurityParameter.class)) {
			final SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation((Class) SecurityParameter.class);
			encode = serializedField.outEncode();
		}
		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
			final ObjectMapper objectMapper = new ObjectMapper();
			try {
				final String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
				return DESHelper.encrypt(result);
			} catch (Exception e) {
				log.info(
						"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常:" + e.getMessage());
			}
		}
		
	}

	return body;
}
 
Example #28
Source File: ApiResultAdvice.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    Object result = apiResultTransformer.changeBody(body, returnType, selectedContentType, selectedConverterType, request, response);
    if (result != null && result instanceof ApiResultWrapper) {
        ApiResultWrapper apiResultWrapper = (ApiResultWrapper) result;
        result= apiResponseFilter.filter(apiResultWrapper,(k,v)->response.getHeaders().set(k.toString(),v.toString()));
    }
    return result;
}
 
Example #29
Source File: PollingSockJsSession.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
		resetRequest();
	}
	else if (!getMessageCache().isEmpty()) {
		flushCache();
	}
	else {
		scheduleHeartbeat();
	}
}
 
Example #30
Source File: SpaceKeyHandshakeInterceptor.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Map<String, Object> attributes) throws Exception {

    String sockJsPath = getSockJsPath(((ServletServerHttpRequest)request).getServletRequest());

    String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");

    attributes.put("spaceKey", pathSegments[0]);

    return true;
}