Here are the examples of the java api org.springframework.http.server.ServletServerHttpRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
50 Examples
19
View Source File : WebSocketHandshakeInterceptor.java
License : Apache License 2.0
Project Creator : XiaoMi
License : Apache License 2.0
Project Creator : XiaoMi
@Nullable
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(false);
} else {
return null;
}
}
19
View Source File : WebSocketHandShakeInterceptor.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
/**
* get request ip,and check it
*
* @param request request
* @return ip address
*/
private String getIpAddress(ServerHttpRequest request) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
String ip = servletRequest.getServletRequest().getHeader("X-Forwarded-For");
log.debug("ServerHttpRequest host: {}", ip);
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
log.debug("unknown ServerHttpRequest host");
return servletRequest.getRemoteAddress().getHostString();
}
String[] ips = ip.split(",");
for (String strIp : ips) {
if (!UNKNOWN.equalsIgnoreCase(strIp)) {
return strIp;
}
}
return "";
}
19
View Source File : MyWebSocketInterceptor.java
License : Apache License 2.0
Project Creator : mengshukeji
License : Apache License 2.0
Project Creator : mengshukeji
private String getParam(ServletServerHttpRequest servletRequest, String key) {
String value = servletRequest.getServletRequest().getParameter(key);
if (value != null) {
value = value.trim();
if (value.length() > 0) {
return value;
}
}
return null;
}
18
View Source File : ResponseEntityExceptionHandlerTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void noHandlerFoundException() {
ServletServerHttpRequest req = new ServletServerHttpRequest(new MockHttpServletRequest("GET", "/resource"));
Exception ex = new NoHandlerFoundException(req.getMethod().toString(), req.getServletRequest().getRequestURI(), req.getHeaders());
testException(ex);
}
18
View Source File : AbstractMessageConverterMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Check if the path has a file extension and whether the extension is
* either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
* {@link ContentNegotiationManager#getAllFileExtensions() registered}.
* If not, and the status is in the 2xx range, a 'Content-Disposition'
* header with a safe attachment file name ("f.txt") is added to prevent
* RFD exploits.
*/
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
HttpHeaders headers = response.getHeaders();
if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
return;
}
try {
int status = response.getServletResponse().getStatus();
if (status < 200 || status > 299) {
return;
}
} catch (Throwable ex) {
// ignore
}
HttpServletRequest servletRequest = request.getServletRequest();
String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);
int index = requestUri.lastIndexOf('/') + 1;
String filename = requestUri.substring(index);
String pathParams = "";
index = filename.indexOf(';');
if (index != -1) {
pathParams = filename.substring(index);
filename = filename.substring(0, index);
}
filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
String ext = StringUtils.getFilenameExtension(filename);
pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
String extInPathParams = StringUtils.getFilenameExtension(pathParams);
if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
}
}
18
View Source File : DefaultServerRequest.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* {@code ServerRequest} implementation based on a {@link HttpServletRequest}.
*
* @author Arjen Poutsma
* @since 5.2
*/
clreplaced DefaultServerRequest implements ServerRequest {
private final ServletServerHttpRequest serverHttpRequest;
private final Headers headers;
private final List<HttpMessageConverter<?>> messageConverters;
private final List<MediaType> allSupportedMediaTypes;
private final MultiValueMap<String, String> params;
private final Map<String, Object> attributes;
public DefaultServerRequest(HttpServletRequest servletRequest, List<HttpMessageConverter<?>> messageConverters) {
this.serverHttpRequest = new ServletServerHttpRequest(servletRequest);
this.messageConverters = Collections.unmodifiableList(new ArrayList<>(messageConverters));
this.allSupportedMediaTypes = allSupportedMediaTypes(messageConverters);
this.headers = new DefaultRequestHeaders(this.serverHttpRequest.getHeaders());
this.params = CollectionUtils.toMultiValueMap(new ServletParametersMap(servletRequest));
this.attributes = new ServletAttributesMap(servletRequest);
}
private static List<MediaType> allSupportedMediaTypes(List<HttpMessageConverter<?>> messageConverters) {
return messageConverters.stream().flatMap(converter -> converter.getSupportedMediaTypes().stream()).sorted(MediaType.SPECIFICITY_COMPARATOR).collect(Collectors.toList());
}
@Override
public String methodName() {
return servletRequest().getMethod();
}
@Override
public URI uri() {
return this.serverHttpRequest.getURI();
}
@Override
public UriBuilder uriBuilder() {
return ServletUriComponentsBuilder.fromRequest(servletRequest());
}
@Override
public Headers headers() {
return this.headers;
}
@Override
public MultiValueMap<String, Cookie> cookies() {
Cookie[] cookies = servletRequest().getCookies();
if (cookies == null) {
cookies = new Cookie[0];
}
MultiValueMap<String, Cookie> result = new LinkedMultiValueMap<>(cookies.length);
for (Cookie cookie : cookies) {
result.add(cookie.getName(), cookie);
}
return result;
}
@Override
public HttpServletRequest servletRequest() {
return this.serverHttpRequest.getServletRequest();
}
@Override
public Optional<InetSocketAddress> remoteAddress() {
return Optional.of(this.serverHttpRequest.getRemoteAddress());
}
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return this.messageConverters;
}
@Override
public <T> T body(Clreplaced<T> bodyType) throws IOException, ServletException {
return bodyInternal(bodyType, bodyType);
}
@Override
public <T> T body(ParameterizedTypeReference<T> bodyType) throws IOException, ServletException {
Type type = bodyType.getType();
return bodyInternal(type, bodyClreplaced(type));
}
static Clreplaced<?> bodyClreplaced(Type type) {
if (type instanceof Clreplaced) {
return (Clreplaced<?>) type;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
if (parameterizedType.getRawType() instanceof Clreplaced) {
return (Clreplaced<?>) parameterizedType.getRawType();
}
}
return Object.clreplaced;
}
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Clreplaced<?> bodyClreplaced) throws ServletException, IOException {
MediaType contentType = this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter = (GenericHttpMessageConverter<T>) messageConverter;
if (genericMessageConverter.canRead(bodyType, bodyClreplaced, contentType)) {
return genericMessageConverter.read(bodyType, bodyClreplaced, this.serverHttpRequest);
}
}
if (messageConverter.canRead(bodyClreplaced, contentType)) {
HttpMessageConverter<T> theConverter = (HttpMessageConverter<T>) messageConverter;
Clreplaced<? extends T> clazz = (Clreplaced<? extends T>) bodyClreplaced;
return theConverter.read(clazz, this.serverHttpRequest);
}
}
throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
@Override
public Optional<Object> attribute(String name) {
return Optional.ofNullable(servletRequest().getAttribute(name));
}
@Override
public Map<String, Object> attributes() {
return this.attributes;
}
@Override
public Optional<String> param(String name) {
return Optional.ofNullable(servletRequest().getParameter(name));
}
@Override
public MultiValueMap<String, String> params() {
return this.params;
}
@Override
public Map<String, String> pathVariables() {
@SuppressWarnings("unchecked")
Map<String, String> pathVariables = (Map<String, String>) servletRequest().getAttribute(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (pathVariables != null) {
return pathVariables;
} else {
return Collections.emptyMap();
}
}
@Override
public HttpSession session() {
return servletRequest().getSession(true);
}
@Override
public Optional<Principal> principal() {
return Optional.ofNullable(this.serverHttpRequest.getPrincipal());
}
/**
* Default implementation of {@link Headers}.
*/
static clreplaced DefaultRequestHeaders implements Headers {
private final HttpHeaders delegate;
public DefaultRequestHeaders(HttpHeaders delegate) {
this.delegate = delegate;
}
@Override
public List<MediaType> accept() {
return this.delegate.getAccept();
}
@Override
public List<Charset> acceptCharset() {
return this.delegate.getAcceptCharset();
}
@Override
public List<Locale.LanguageRange> acceptLanguage() {
return this.delegate.getAcceptLanguage();
}
@Override
public OptionalLong contentLength() {
long value = this.delegate.getContentLength();
return (value != -1 ? OptionalLong.of(value) : OptionalLong.empty());
}
@Override
public Optional<MediaType> contentType() {
return Optional.ofNullable(this.delegate.getContentType());
}
@Override
public InetSocketAddress host() {
return this.delegate.getHost();
}
@Override
public List<HttpRange> range() {
return this.delegate.getRange();
}
@Override
public List<String> header(String headerName) {
List<String> headerValues = this.delegate.get(headerName);
return (headerValues != null ? headerValues : Collections.emptyList());
}
@Override
public HttpHeaders asHttpHeaders() {
return HttpHeaders.readOnlyHttpHeaders(this.delegate);
}
@Override
public String toString() {
return this.delegate.toString();
}
}
private static final clreplaced ServletParametersMap extends AbstractMap<String, List<String>> {
private final HttpServletRequest servletRequest;
private ServletParametersMap(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
@NotNull
@Override
public Set<Entry<String, List<String>>> entrySet() {
return this.servletRequest.getParameterMap().entrySet().stream().map(entry -> {
List<String> value = Arrays.asList(entry.getValue());
return new SimpleImmutableEntry<>(entry.getKey(), value);
}).collect(Collectors.toSet());
}
@Override
public int size() {
return this.servletRequest.getParameterMap().size();
}
@Override
public List<String> get(Object key) {
String name = (String) key;
String[] parameterValues = this.servletRequest.getParameterValues(name);
if (!ObjectUtils.isEmpty(parameterValues)) {
return Arrays.asList(parameterValues);
} else {
return Collections.emptyList();
}
}
@Override
public List<String> put(String key, List<String> value) {
throw new UnsupportedOperationException();
}
@Override
public List<String> remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
private static final clreplaced ServletAttributesMap extends AbstractMap<String, Object> {
private final HttpServletRequest servletRequest;
private ServletAttributesMap(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
@Override
public boolean containsKey(Object key) {
String name = (String) key;
return this.servletRequest.getAttribute(name) != null;
}
@Override
public void clear() {
List<String> attributeNames = Collections.list(this.servletRequest.getAttributeNames());
attributeNames.forEach(this.servletRequest::removeAttribute);
}
@NotNull
@Override
public Set<Entry<String, Object>> entrySet() {
return Collections.list(this.servletRequest.getAttributeNames()).stream().map(name -> {
Object value = this.servletRequest.getAttribute(name);
return new SimpleImmutableEntry<>(name, value);
}).collect(Collectors.toSet());
}
@Override
public Object get(Object key) {
String name = (String) key;
return this.servletRequest.getAttribute(name);
}
@Override
public Object put(String key, Object value) {
Object oldValue = this.servletRequest.getAttribute(key);
this.servletRequest.setAttribute(key, value);
return oldValue;
}
@Override
public Object remove(Object key) {
String name = (String) key;
Object value = this.servletRequest.getAttribute(name);
this.servletRequest.removeAttribute(name);
return value;
}
}
}
18
View Source File : DefaultServerRequest.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* {@code ServerRequest} implementation based on a {@link HttpServletRequest}.
*
* @author Arjen Poutsma
* @since 5.2
*/
clreplaced DefaultServerRequest implements ServerRequest {
private final ServletServerHttpRequest serverHttpRequest;
private final Headers headers;
private final List<HttpMessageConverter<?>> messageConverters;
private final List<MediaType> allSupportedMediaTypes;
private final MultiValueMap<String, String> params;
private final Map<String, Object> attributes;
public DefaultServerRequest(HttpServletRequest servletRequest, List<HttpMessageConverter<?>> messageConverters) {
this.serverHttpRequest = new ServletServerHttpRequest(servletRequest);
this.messageConverters = Collections.unmodifiableList(new ArrayList<>(messageConverters));
this.allSupportedMediaTypes = allSupportedMediaTypes(messageConverters);
this.headers = new DefaultRequestHeaders(this.serverHttpRequest.getHeaders());
this.params = CollectionUtils.toMultiValueMap(new ServletParametersMap(servletRequest));
this.attributes = new ServletAttributesMap(servletRequest);
}
private static List<MediaType> allSupportedMediaTypes(List<HttpMessageConverter<?>> messageConverters) {
return messageConverters.stream().flatMap(converter -> converter.getSupportedMediaTypes().stream()).sorted(MediaType.SPECIFICITY_COMPARATOR).collect(Collectors.toList());
}
@Override
public String methodName() {
return servletRequest().getMethod();
}
@Override
public URI uri() {
return this.serverHttpRequest.getURI();
}
@Override
public UriBuilder uriBuilder() {
return ServletUriComponentsBuilder.fromRequest(servletRequest());
}
@Override
public String path() {
String path = (String) servletRequest().getAttribute(HandlerMapping.LOOKUP_PATH);
if (path == null) {
UrlPathHelper helper = new UrlPathHelper();
path = helper.getLookupPathForRequest(servletRequest());
}
return path;
}
@Override
public Headers headers() {
return this.headers;
}
@Override
public MultiValueMap<String, Cookie> cookies() {
Cookie[] cookies = servletRequest().getCookies();
if (cookies == null) {
cookies = new Cookie[0];
}
MultiValueMap<String, Cookie> result = new LinkedMultiValueMap<>(cookies.length);
for (Cookie cookie : cookies) {
result.add(cookie.getName(), cookie);
}
return result;
}
@Override
public HttpServletRequest servletRequest() {
return this.serverHttpRequest.getServletRequest();
}
@Override
public Optional<InetSocketAddress> remoteAddress() {
return Optional.of(this.serverHttpRequest.getRemoteAddress());
}
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return this.messageConverters;
}
@Override
public <T> T body(Clreplaced<T> bodyType) throws IOException, ServletException {
return bodyInternal(bodyType, bodyType);
}
@Override
public <T> T body(ParameterizedTypeReference<T> bodyType) throws IOException, ServletException {
Type type = bodyType.getType();
return bodyInternal(type, bodyClreplaced(type));
}
static Clreplaced<?> bodyClreplaced(Type type) {
if (type instanceof Clreplaced) {
return (Clreplaced<?>) type;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
if (parameterizedType.getRawType() instanceof Clreplaced) {
return (Clreplaced<?>) parameterizedType.getRawType();
}
}
return Object.clreplaced;
}
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Clreplaced<?> bodyClreplaced) throws ServletException, IOException {
MediaType contentType = this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter = (GenericHttpMessageConverter<T>) messageConverter;
if (genericMessageConverter.canRead(bodyType, bodyClreplaced, contentType)) {
return genericMessageConverter.read(bodyType, bodyClreplaced, this.serverHttpRequest);
}
}
if (messageConverter.canRead(bodyClreplaced, contentType)) {
HttpMessageConverter<T> theConverter = (HttpMessageConverter<T>) messageConverter;
Clreplaced<? extends T> clazz = (Clreplaced<? extends T>) bodyClreplaced;
return theConverter.read(clazz, this.serverHttpRequest);
}
}
throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
@Override
public Optional<Object> attribute(String name) {
return Optional.ofNullable(servletRequest().getAttribute(name));
}
@Override
public Map<String, Object> attributes() {
return this.attributes;
}
@Override
public Optional<String> param(String name) {
return Optional.ofNullable(servletRequest().getParameter(name));
}
@Override
public MultiValueMap<String, String> params() {
return this.params;
}
@Override
public Map<String, String> pathVariables() {
@SuppressWarnings("unchecked")
Map<String, String> pathVariables = (Map<String, String>) servletRequest().getAttribute(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (pathVariables != null) {
return pathVariables;
} else {
return Collections.emptyMap();
}
}
@Override
public HttpSession session() {
return servletRequest().getSession(true);
}
@Override
public Optional<Principal> principal() {
return Optional.ofNullable(this.serverHttpRequest.getPrincipal());
}
/**
* Default implementation of {@link Headers}.
*/
static clreplaced DefaultRequestHeaders implements Headers {
private final HttpHeaders delegate;
public DefaultRequestHeaders(HttpHeaders delegate) {
this.delegate = delegate;
}
@Override
public List<MediaType> accept() {
return this.delegate.getAccept();
}
@Override
public List<Charset> acceptCharset() {
return this.delegate.getAcceptCharset();
}
@Override
public List<Locale.LanguageRange> acceptLanguage() {
return this.delegate.getAcceptLanguage();
}
@Override
public OptionalLong contentLength() {
long value = this.delegate.getContentLength();
return (value != -1 ? OptionalLong.of(value) : OptionalLong.empty());
}
@Override
public Optional<MediaType> contentType() {
return Optional.ofNullable(this.delegate.getContentType());
}
@Override
public InetSocketAddress host() {
return this.delegate.getHost();
}
@Override
public List<HttpRange> range() {
return this.delegate.getRange();
}
@Override
public List<String> header(String headerName) {
List<String> headerValues = this.delegate.get(headerName);
return (headerValues != null ? headerValues : Collections.emptyList());
}
@Override
public HttpHeaders asHttpHeaders() {
return HttpHeaders.readOnlyHttpHeaders(this.delegate);
}
@Override
public String toString() {
return this.delegate.toString();
}
}
private static final clreplaced ServletParametersMap extends AbstractMap<String, List<String>> {
private final HttpServletRequest servletRequest;
private ServletParametersMap(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
@Override
public Set<Entry<String, List<String>>> entrySet() {
return this.servletRequest.getParameterMap().entrySet().stream().map(entry -> {
List<String> value = Arrays.asList(entry.getValue());
return new SimpleImmutableEntry<>(entry.getKey(), value);
}).collect(Collectors.toSet());
}
@Override
public int size() {
return this.servletRequest.getParameterMap().size();
}
@Override
public List<String> get(Object key) {
String name = (String) key;
String[] parameterValues = this.servletRequest.getParameterValues(name);
if (!ObjectUtils.isEmpty(parameterValues)) {
return Arrays.asList(parameterValues);
} else {
return Collections.emptyList();
}
}
@Override
public List<String> put(String key, List<String> value) {
throw new UnsupportedOperationException();
}
@Override
public List<String> remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
private static final clreplaced ServletAttributesMap extends AbstractMap<String, Object> {
private final HttpServletRequest servletRequest;
private ServletAttributesMap(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
@Override
public boolean containsKey(Object key) {
String name = (String) key;
return this.servletRequest.getAttribute(name) != null;
}
@Override
public void clear() {
List<String> attributeNames = Collections.list(this.servletRequest.getAttributeNames());
attributeNames.forEach(this.servletRequest::removeAttribute);
}
@Override
public Set<Entry<String, Object>> entrySet() {
return Collections.list(this.servletRequest.getAttributeNames()).stream().map(name -> {
Object value = this.servletRequest.getAttribute(name);
return new SimpleImmutableEntry<>(name, value);
}).collect(Collectors.toSet());
}
@Override
public Object get(Object key) {
String name = (String) key;
return this.servletRequest.getAttribute(name);
}
@Override
public Object put(String key, Object value) {
Object oldValue = this.servletRequest.getAttribute(key);
this.servletRequest.setAttribute(key, value);
return oldValue;
}
@Override
public Object remove(Object key) {
String name = (String) key;
Object value = this.servletRequest.getAttribute(name);
this.servletRequest.removeAttribute(name);
return value;
}
}
}
18
View Source File : UserAttributeHandshakeInterceptor.java
License : MIT License
Project Creator : Hccake
License : MIT License
Project Creator : Hccake
/**
* Invoked before the handshake is processed.
* @param request the current request
* @param response the current response
* @param wsHandler the target WebSocket handler
* @param attributes the attributes from the HTTP handshake to replacedociate with the
* WebSocket session; the provided attributes are copied, the original map is not
* used.
* @return whether to proceed with the handshake ({@code true}) or abort
* ({@code false})
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
String accessToken = null;
// 获得 accessToken
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
accessToken = serverRequest.getServletRequest().getParameter(AdminWebSocketConstants.TOKEN_ATTR_NAME);
}
// 由于 WebSocket 握手是由 http 升级的,携带 token 已经被 Security 拦截验证了,所以可以直接获取到用户
SysUser sysUser = SecurityUtils.getSysUser();
attributes.put(AdminWebSocketConstants.TOKEN_ATTR_NAME, accessToken);
attributes.put(AdminWebSocketConstants.USER_KEY_ATTR_NAME, sysUser.getUserId());
return true;
}
17
View Source File : TerminalHandShaker.java
License : Apache License 2.0
Project Creator : yile0906
License : Apache License 2.0
Project Creator : yile0906
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession();
attributes.put("cols", servletRequest.getServletRequest().getParameter("cols"));
attributes.put("rows", servletRequest.getServletRequest().getParameter("rows"));
attributes.put("width", servletRequest.getServletRequest().getParameter("width"));
attributes.put("height", servletRequest.getServletRequest().getParameter("height"));
attributes.put(SSH_SESSION_ID, session.getAttribute(SSH_SESSION_ID));
attributes.put(HTTP_SESSION_ID, session.getAttribute(HTTP_SESSION_ID));
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
17
View Source File : WebSocketInterceptor.java
License : MIT License
Project Creator : yidao620c
License : MIT License
Project Creator : yidao620c
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2, Map<String, Object> arg3) throws Exception {
// 将ServerHttpRequest转换成request请求相关的类,用来获取request域中的用户信息
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpServletRequest httpRequest = servletRequest.getServletRequest();
}
logger.info("beforeHandshake完成");
return true;
}
17
View Source File : HttpSessionHandshakeInterceptor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Nullable
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(isCreateSession());
}
return null;
}
17
View Source File : AbstractMessageConverterMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* 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);
}
17
View Source File : SessionRepositoryMessageInterceptor.java
License : Apache License 2.0
Project Creator : ralscha
License : Apache License 2.0
Project Creator : ralscha
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
attributes.put(SPRING_SESSION_ID_ATTR_NAME, session.getId());
}
}
return true;
}
17
View Source File : WebSocketInterceptor.java
License : MIT License
Project Creator : qunarcorp
License : MIT License
Project Creator : qunarcorp
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
HttpSession session = serverHttpRequest.getServletRequest().getSession();
if (session != null) {
// String userId = (String) session.getAttribute("userId");
String userId = SecurityUtils.currentUsername();
if (userId == null) {
userId = "WEBSOCKET_USERNAME_IS_NULL";
}
map.put("userId", userId);
}
}
return true;
}
17
View Source File : MyWebSocketInterceptor.java
License : Apache License 2.0
Project Creator : mengshukeji
License : Apache License 2.0
Project Creator : mengshukeji
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// 解决The extension [x-webkit-deflate-frame] is not supported问题
// if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
// request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
// }
// websocket系统启动连接程序,启动的时候就会把他的session值传过来,放入到websocketsession(websocket的一个内置服务器)里面
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
log.info("beforeHandshake--session:{}", session);
// 用户token
String token = getParam(servletRequest, WSUserModel.USER_TOKEN);
// 文档id
String gridKey = getParam(servletRequest, WSUserModel.USER_GRIDKEY);
if (null != token && null != gridKey) {
// 验证用户信息
String gridKeys = MyURLUtil.urlDecode(gridKey);
String _checkStr = check(gridKeys);
log.info("link gridKey:{};userToken:{};check:{}", gridKeys, token, _checkStr);
if (_checkStr.length() > 0) {
return false;
}
attributes.put(WSUserModel.USER_TOKEN, token);
attributes.put(WSUserModel.USER_GRIDKEY, gridKey);
} else {
return false;
}
return true;
}
17
View Source File : HttpSessionHandshakeInterceptor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(isCreateSession());
}
return null;
}
17
View Source File : HttpHandshakeInterceptor.java
License : GNU General Public License v2.0
Project Creator : LandvibeDev
License : GNU General Public License v2.0
Project Creator : LandvibeDev
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession();
if (session.getAttribute("user") != null) {
System.out.println(session.getAttribute("user"));
attributes.put("user", session.getAttribute("user"));
attributes.put("file", new CodeRoom());
}
}
return true;
}
17
View Source File : WebSocketInterceptor.java
License : GNU General Public License v3.0
Project Creator : gxing19
License : GNU General Public License v3.0
Project Creator : gxing19
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println("=====================握手前拦截===========================");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
String userName = (String) session.getAttribute("userName");
if (userName == null) {
userName = "WEBSOCKET_USERNAME_IS_NULL";
}
attributes.put("userName", userName);
}
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
17
View Source File : WebSocketInterceptor.java
License : GNU General Public License v3.0
Project Creator : gxing19
License : GNU General Public License v3.0
Project Creator : gxing19
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println("=====================握手前拦截===========================");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
String userName = (String) session.getAttribute("username");
}
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
17
View Source File : WebSocketInterceptor.java
License : Apache License 2.0
Project Creator : EdgeGallery
License : Apache License 2.0
Project Creator : EdgeGallery
@Override
public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
if (serverHttpRequest instanceof ServletServerHttpRequest) {
ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
// 生成一个UUID
String uuid = UUID.randomUUID().toString().replace("-", "");
// 将uuid放到websocketsession中
map.put(ConstantPool.USER_UUID_KEY, uuid);
return true;
} else {
return false;
}
}
17
View Source File : HttpHandshakeInterceptor.java
License : GNU General Public License v3.0
Project Creator : aaronchen2k
License : GNU General Public License v3.0
Project Creator : aaronchen2k
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession httpSession = servletRequest.getServletRequest().getSession(true);
String test = (String) httpSession.getAttribute("TEST");
TstUser user = (TstUser) SecurityUtils.getSubject().getPrincipal();
if (user != null) {
attributes.put(WsConstant.WS_USER_KEY, user);
return true;
}
}
return false;
}
16
View Source File : RequestResponseBodyMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter, Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.clreplaced);
replacedert.state(servletRequest != null, "No HttpServletRequest");
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
if (arg == null && checkRequired(parameter)) {
throw new HttpMessageNotReadableException("Required request body is missing: " + parameter.getExecutable().toGenericString(), inputMessage);
}
return arg;
}
16
View Source File : ReturnValueHandler.java
License : GNU General Public License v2.0
Project Creator : sanri1993
License : GNU General Public License v2.0
Project Creator : sanri1993
@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);
Executable executable = returnType.getExecutable();
Type type = executable.getAnnotatedReturnType().getType();
if (type == Void.TYPE) {
returnValue = ResponseDto.ok();
} else if (type != ResponseDto.clreplaced) {
returnValue = ResponseDto.ok().data(returnValue);
}
// Try even with null return value. ResponseBodyAdvice could get involved.
writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
16
View Source File : RequestResponseBodyMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.clreplaced);
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
Object arg = readWithMessageConverters(inputMessage, methodParam, paramType);
if (arg == null) {
if (methodParam.getParameterAnnotation(RequestBody.clreplaced).required()) {
throw new HttpMessageNotReadableException("Required request body is missing: " + methodParam.getMethod().toGenericString());
}
}
return arg;
}
16
View Source File : AbstractMessageConverterMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* 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);
}
15
View Source File : DefaultHandlerExceptionResolverTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void handleNoHandlerFoundException() throws Exception {
ServletServerHttpRequest req = new ServletServerHttpRequest(new MockHttpServletRequest("GET", "/resource"));
NoHandlerFoundException ex = new NoHandlerFoundException(req.getMethod().name(), req.getServletRequest().getRequestURI(), req.getHeaders());
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
replacedertNotNull("No ModelAndView returned", mav);
replacedertTrue("No Empty ModelAndView returned", mav.isEmpty());
replacedertEquals("Invalid status code", 404, response.getStatus());
}
15
View Source File : RequestResponseBodyMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
mavContainer.setRequestHandled(true);
ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
// Try even with null return value. ResponseBodyAdvice could get involved.
writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
15
View Source File : HttpEntityMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws IOException, HttpMediaTypeNotSupportedException {
ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
Type paramType = getHttpEnreplacedyType(parameter);
if (paramType == null) {
throw new IllegalArgumentException("HttpEnreplacedy parameter '" + parameter.getParameterName() + "' in method " + parameter.getMethod() + " is not parameterized");
}
Object body = readWithMessageConverters(webRequest, parameter, paramType);
if (RequestEnreplacedy.clreplaced == parameter.getParameterType()) {
return new RequestEnreplacedy<>(body, inputMessage.getHeaders(), inputMessage.getMethod(), inputMessage.getURI());
} else {
return new HttpEnreplacedy<>(body, inputMessage.getHeaders());
}
}
15
View Source File : HttpEntityMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
ServletWebRequest servletWebRequest = new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
HttpHeaders responseHeaders = response.getHeaders();
String etag = responseHeaders.getETag();
long lastModifiedTimestamp = responseHeaders.getLastModified();
if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
responseHeaders.remove(HttpHeaders.ETAG);
responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
}
return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
15
View Source File : DefaultHandlerExceptionResolverTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void handleNoHandlerFoundException() throws Exception {
ServletServerHttpRequest req = new ServletServerHttpRequest(new MockHttpServletRequest("GET", "/resource"));
NoHandlerFoundException ex = new NoHandlerFoundException(req.getMethod().name(), req.getServletRequest().getRequestURI(), req.getHeaders());
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
replacedertThat(mav).as("No ModelAndView returned").isNotNull();
replacedertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
replacedertThat(response.getStatus()).as("Invalid status code").isEqualTo(404);
}
14
View Source File : WebSocketInterceptor.java
License : MIT License
Project Creator : TaleLin
License : MIT License
Project Creator : TaleLin
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest httpServletRequest = (ServletServerHttpRequest) request;
String tokenStr = httpServletRequest.getServletRequest().getParameter("token");
if (tokenStr == null || tokenStr.isEmpty()) {
writeMessageToBody(response, "authorization field is required");
return false;
}
Map<String, Claim> claims;
try {
claims = jwt.decodeAccessToken(tokenStr);
} catch (TokenExpiredException e) {
writeMessageToBody(response, "token is expired");
return false;
} catch (AlgorithmMismatchException | SignatureVerificationException | JWTDecodeException | InvalidClaimException e) {
writeMessageToBody(response, "token is invalid");
return false;
}
if (claims == null) {
writeMessageToBody(response, "token is invalid, can't be decode");
return false;
}
int idenreplacedy = claims.get("idenreplacedy").asInt();
UserDO user = userService.getById(idenreplacedy);
if (user == null) {
writeMessageToBody(response, "user is not found");
return false;
}
attributes.put(USER_KEY, user);
return true;
}
return false;
}
14
View Source File : WebSocketInterceptor.java
License : Apache License 2.0
Project Creator : open-hand
License : Apache License 2.0
Project Creator : open-hand
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
// 获取所有拦截器
Map<String, SocketInterceptor> interceptorMap = getInterceptors();
String processor = serverHttpRequest.getServletRequest().getParameter(WebSocketConstant.Attributes.PROCESSOR);
if (StringUtils.isNotBlank(processor) && interceptorMap.containsKey(processor)) {
SocketInterceptor interceptor = interceptorMap.get(processor);
// 执行group对应的拦截器
interceptor.afterHandshake(request, response, wsHandler, exception);
}
interceptorMap.get(WebSocketConstant.DEFAULT_PROCESSOR).afterHandshake(request, response, wsHandler, exception);
}
}
14
View Source File : DefaultCorsProcessor.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
@Override
@SuppressWarnings("resource")
public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (!CorsUtils.isCorsRequest(request)) {
return true;
}
ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
if (responseHasCors(serverResponse)) {
logger.trace("Skip: response already contains \"Access-Control-Allow-Origin\"");
return true;
}
ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
if (WebUtils.isSameOrigin(serverRequest)) {
logger.trace("Skip: request is from same origin");
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);
}
14
View Source File : HttpEntityMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
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;
}
14
View Source File : HttpEntityMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws IOException, HttpMediaTypeNotSupportedException {
ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
Type paramType = getHttpEnreplacedyType(parameter);
Object body = readWithMessageConverters(webRequest, parameter, paramType);
if (RequestEnreplacedy.clreplaced == parameter.getParameterType()) {
return new RequestEnreplacedy<Object>(body, inputMessage.getHeaders(), inputMessage.getMethod(), inputMessage.getURI());
} else {
return new HttpEnreplacedy<Object>(body, inputMessage.getHeaders());
}
}
14
View Source File : DefaultCorsProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@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);
}
11
View Source File : DispatcherFilterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void handledByDispatcher() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
HttpServletResponse response = new MockHttpServletResponse();
willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.clreplaced), any(ServerHttpResponse.clreplaced));
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;
replacedertThat(actualRequest.getServletRequest()).isEqualTo(request);
replacedertThat(actualResponse.getServletResponse()).isEqualTo(response);
}
10
View Source File : ProfileController.java
License : MIT License
Project Creator : wayn111
License : MIT License
Project Creator : wayn111
/**
* 更新个人资料
*
* @param request
* @param user
* @return
*/
@RepeatSubmit
@ResponseBody
@PostMapping("updateUser")
public Response updateUser(HttpServletRequest request, User user) {
ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(request);
servletServerHttpRequest.getPrincipal();
if (!userService.updateById(user)) {
return Response.error("更新用户信息失败");
}
Subject subject = SecurityUtils.getSubject();
String realmName = subject.getPrincipals().getRealmNames().iterator().next();
PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(userService.getById(user.getId()), realmName);
// 重新加载Principal
subject.runAs(newPrincipalCollection);
return Response.success("修改用户信息成功!");
}
10
View Source File : AbstractMessageConverterMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Check if the path has a file extension and whether the extension is
* either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
* {@link ContentNegotiationManager#getAllFileExtensions() registered}.
* If not, and the status is in the 2xx range, a 'Content-Disposition'
* header with a safe attachment file name ("f.txt") is added to prevent
* RFD exploits.
*/
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
HttpHeaders headers = response.getHeaders();
if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
return;
}
try {
int status = response.getServletResponse().getStatus();
if (status < 200 || status > 299) {
return;
}
} catch (Throwable ex) {
// Ignore
}
HttpServletRequest servletRequest = request.getServletRequest();
String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);
int index = requestUri.lastIndexOf('/') + 1;
String filename = requestUri.substring(index);
String pathParams = "";
index = filename.indexOf(';');
if (index != -1) {
pathParams = filename.substring(index);
filename = filename.substring(0, index);
}
filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
String ext = StringUtils.getFilenameExtension(filename);
pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
String extInPathParams = StringUtils.getFilenameExtension(pathParams);
if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
}
}
10
View Source File : PartialUpdateArgumentResolver.java
License : GNU General Public License v3.0
Project Creator : countrogue
License : GNU General Public License v3.0
Project Creator : countrogue
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
ServletServerHttpRequest req = createInputMessage(webRequest);
Patch patch = parameter.getMethodAnnotation(Patch.clreplaced);
Clreplaced serviceClreplaced = patch.service();
Clreplaced idClreplaced = patch.id();
Object service = context.getBean(serviceClreplaced);
String idStr = getPathVariables(webRequest).get("id");
Object id = idClreplaced.cast(idStr);
Method method = ReflectionUtils.findMethod(serviceClreplaced, "find", idClreplaced);
Object obj = ReflectionUtils.invokeMethod(method, service, id);
obj = readJavaType(obj, req);
return obj;
}
9
View Source File : HttpEntityMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void handleReturnValue(@Nullable 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);
replacedert.isInstanceOf(HttpEnreplacedy.clreplaced, returnValue);
HttpEnreplacedy<?> responseEnreplacedy = (HttpEnreplacedy<?>) returnValue;
HttpHeaders outputHeaders = outputMessage.getHeaders();
HttpHeaders enreplacedyHeaders = responseEnreplacedy.getHeaders();
if (!enreplacedyHeaders.isEmpty()) {
enreplacedyHeaders.forEach((key, value) -> {
if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
List<String> values = getVaryRequestHeadersToAdd(outputHeaders, enreplacedyHeaders);
if (!values.isEmpty()) {
outputHeaders.setVary(values);
}
} else {
outputHeaders.put(key, value);
}
});
}
if (responseEnreplacedy instanceof ResponseEnreplacedy) {
int returnStatus = ((ResponseEnreplacedy<?>) responseEnreplacedy).getStatusCodeValue();
outputMessage.getServletResponse().setStatus(returnStatus);
if (returnStatus == 200) {
if (SAFE_METHODS.contains(inputMessage.getMethod()) && isResourceNotModified(inputMessage, outputMessage)) {
// Ensure headers are flushed, no body should be written.
outputMessage.flush();
ShallowEtagHeaderFilter.disableContentCaching(inputMessage.getServletRequest());
// Skip call to converters, as they may update the body.
return;
}
} else if (returnStatus / 100 == 3) {
String location = outputHeaders.getFirst("location");
if (location != null) {
saveFlashAttributes(mavContainer, webRequest, location);
}
}
}
// Try even with null body. ResponseBodyAdvice could get involved.
writeWithMessageConverters(responseEnreplacedy.getBody(), returnType, inputMessage, outputMessage);
// Ensure headers are flushed even if no body was written.
outputMessage.flush();
}
9
View Source File : WebSocketInterceptor.java
License : Apache License 2.0
Project Creator : open-hand
License : Apache License 2.0
Project Creator : open-hand
/**
* handler处理前调用,attributes属性最终在WebSocketSession里,可能通过webSocketSession.getAttributes().get(key值)获得
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
boolean result = true;
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
// 将所有路径参数添加到attributes
for (Map.Entry<String, String[]> entry : serverHttpRequest.getServletRequest().getParameterMap().entrySet()) {
attributes.put(entry.getKey(), entry.getValue()[0]);
}
// 从header取token
List<String> list = serverHttpRequest.getHeaders().get(HEADER_AUTH);
if (CollectionUtils.isNotEmpty(list)) {
String accessToken = list.get(0);
if (StringUtils.startsWithIgnoreCase(accessToken, TOKEN_PREFIX)) {
accessToken = accessToken.substring(TOKEN_PREFIX.length());
}
attributes.put(WebSocketConstant.Attributes.TOKEN, accessToken);
}
if (!attributes.containsKey(WebSocketConstant.Attributes.SECRET_KEY) && !attributes.containsKey(WebSocketConstant.Attributes.TOKEN)) {
// 未携带密钥和token,连接断开
return false;
}
// 密钥链接
if (attributes.containsKey(WebSocketConstant.Attributes.SECRET_KEY)) {
// 验证密钥
String key = ApplicationContextHelper.getContext().getBean(WebSocketConfig.clreplaced).getSecretKey();
if (!Objects.equals(attributes.get(WebSocketConstant.Attributes.SECRET_KEY), key)) {
return false;
}
}
// 获取所有拦截器
Map<String, SocketInterceptor> interceptorMap = getInterceptors();
String processor = String.valueOf(attributes.get(WebSocketConstant.Attributes.PROCESSOR));
if (StringUtils.isNotBlank(processor) && interceptorMap.containsKey(processor)) {
SocketInterceptor interceptor = interceptorMap.get(processor);
// 执行type对应的拦截器
result = interceptor.beforeHandshake(request, response, wsHandler, attributes);
}
// group拦截器通过,执行默认拦截器
if (result) {
return interceptorMap.get(WebSocketConstant.DEFAULT_PROCESSOR).beforeHandshake(request, response, wsHandler, attributes);
}
}
return false;
}
9
View Source File : HttpEntityMethodProcessor.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
@Override
public void handleReturnValue(@Nullable 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);
replacedert.isInstanceOf(HttpEnreplacedy.clreplaced, returnValue);
HttpEnreplacedy<?> responseEnreplacedy = (HttpEnreplacedy<?>) returnValue;
HttpHeaders outputHeaders = outputMessage.getHeaders();
HttpHeaders enreplacedyHeaders = responseEnreplacedy.getHeaders();
if (!enreplacedyHeaders.isEmpty()) {
enreplacedyHeaders.forEach((key, value) -> {
if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
List<String> values = getVaryRequestHeadersToAdd(outputHeaders, enreplacedyHeaders);
if (!values.isEmpty()) {
outputHeaders.setVary(values);
}
} else {
outputHeaders.put(key, value);
}
});
}
if (responseEnreplacedy instanceof ResponseEnreplacedy) {
int returnStatus = ((ResponseEnreplacedy<?>) responseEnreplacedy).getStatusCodeValue();
outputMessage.getServletResponse().setStatus(returnStatus);
if (returnStatus == 200) {
if (SAFE_METHODS.contains(inputMessage.getMethod()) && isResourceNotModified(inputMessage, outputMessage)) {
// Ensure headers are flushed, no body should be written.
outputMessage.flush();
// Skip call to converters, as they may update the body.
return;
}
} else if (returnStatus / 100 == 3) {
String location = outputHeaders.getFirst("location");
if (location != null) {
saveFlashAttributes(mavContainer, webRequest, location);
}
}
}
// Try even with null body. ResponseBodyAdvice could get involved.
writeWithMessageConverters(responseEnreplacedy.getBody(), returnType, inputMessage, outputMessage);
// Ensure headers are flushed even if no body was written.
outputMessage.flush();
}
8
View Source File : HttpEntityMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@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);
replacedert.isInstanceOf(HttpEnreplacedy.clreplaced, returnValue);
HttpEnreplacedy<?> responseEnreplacedy = (HttpEnreplacedy<?>) returnValue;
HttpHeaders enreplacedyHeaders = responseEnreplacedy.getHeaders();
if (!enreplacedyHeaders.isEmpty()) {
outputMessage.getHeaders().putAll(enreplacedyHeaders);
}
Object body = responseEnreplacedy.getBody();
if (responseEnreplacedy instanceof ResponseEnreplacedy) {
outputMessage.setStatusCode(((ResponseEnreplacedy<?>) responseEnreplacedy).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();
}
7
View Source File : AbstractMessageConverterMethodProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Writes the given return type to the given output message.
* @param value the value to write to the output message
* @param returnType the type of the value
* @param inputMessage the input messages. Used to inspect the {@code Accept} header.
* @param outputMessage the output message to write to
* @throws IOException thrown in case of I/O errors
* @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated
* by the {@code Accept} header on the request cannot be met by the message converters
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
Object body;
Clreplaced<?> valueType;
Type targetType;
if (value instanceof CharSequence) {
body = value.toString();
valueType = String.clreplaced;
targetType = String.clreplaced;
} else {
body = value;
valueType = getReturnValueType(body, returnType);
targetType = GenericTypeResolver.resolveType(getGenericType(returnType), returnType.getContainingClreplaced());
}
if (isResourceType(value, returnType)) {
outputMessage.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
if (value != null && inputMessage.getHeaders().getFirst(HttpHeaders.RANGE) != null && outputMessage.getServletResponse().getStatus() == 200) {
Resource resource = (Resource) value;
try {
List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
outputMessage.getServletResponse().setStatus(HttpStatus.PARTIAL_CONTENT.value());
body = HttpRange.toResourceRegions(httpRanges, resource);
valueType = body.getClreplaced();
targetType = RESOURCE_REGION_LIST_TYPE;
} catch (IllegalArgumentException ex) {
outputMessage.getHeaders().set(HttpHeaders.CONTENT_RANGE, "bytes */" + resource.contentLength());
outputMessage.getServletResponse().setStatus(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value());
}
}
}
MediaType selectedMediaType = null;
MediaType contentType = outputMessage.getHeaders().getContentType();
if (contentType != null && contentType.isConcrete()) {
if (logger.isDebugEnabled()) {
logger.debug("Found 'Content-Type:" + contentType + "' in response");
}
selectedMediaType = contentType;
} else {
HttpServletRequest request = inputMessage.getServletRequest();
List<MediaType> acceptableTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleTypes = getProducibleMediaTypes(request, valueType, targetType);
if (body != null && producibleTypes.isEmpty()) {
throw new HttpMessageNotWritableException("No converter found for return value of type: " + valueType);
}
List<MediaType> mediaTypesToUse = new ArrayList<>();
for (MediaType requestedType : acceptableTypes) {
for (MediaType producibleType : producibleTypes) {
if (requestedType.isCompatibleWith(producibleType)) {
mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
}
}
}
if (mediaTypesToUse.isEmpty()) {
if (body != null) {
throw new HttpMediaTypeNotAcceptableException(producibleTypes);
}
if (logger.isDebugEnabled()) {
logger.debug("No match for " + acceptableTypes + ", supported: " + producibleTypes);
}
return;
}
MediaType.sortBySpecificityAndQuality(mediaTypesToUse);
for (MediaType mediaType : mediaTypesToUse) {
if (mediaType.isConcrete()) {
selectedMediaType = mediaType;
break;
} else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
break;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using '" + selectedMediaType + "', given " + acceptableTypes + " and supported " + producibleTypes);
}
}
if (selectedMediaType != null) {
selectedMediaType = selectedMediaType.removeQualityValue();
for (HttpMessageConverter<?> converter : this.messageConverters) {
GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
if (genericConverter != null ? ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : converter.canWrite(valueType, selectedMediaType)) {
body = getAdvice().beforeBodyWrite(body, returnType, selectedMediaType, (Clreplaced<? extends HttpMessageConverter<?>>) converter.getClreplaced(), inputMessage, outputMessage);
if (body != null) {
Object theBody = body;
LogFormatUtils.traceDebug(logger, traceOn -> "Writing [" + LogFormatUtils.formatValue(theBody, !traceOn) + "]");
addContentDispositionHeader(inputMessage, outputMessage);
if (genericConverter != null) {
genericConverter.write(body, targetType, selectedMediaType, outputMessage);
} else {
((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Nothing to write: null body");
}
}
return;
}
}
}
if (body != null) {
throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
}
}
7
View Source File : AbstractMessageConverterMethodProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Writes the given return type to the given output message.
* @param returnValue the value to write to the output message
* @param returnType the type of the value
* @param inputMessage the input messages. Used to inspect the {@code Accept} header.
* @param outputMessage the output message to write to
* @throws IOException thrown in case of I/O errors
* @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
* the request cannot be met by the message converters
*/
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
Clreplaced<?> returnValueClreplaced = getReturnValueType(returnValue, returnType);
Type returnValueType = getGenericType(returnType);
HttpServletRequest servletRequest = inputMessage.getServletRequest();
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClreplaced, returnValueType);
if (returnValue != null && producibleMediaTypes.isEmpty()) {
throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClreplaced);
}
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
for (MediaType requestedType : requestedMediaTypes) {
for (MediaType producibleType : producibleMediaTypes) {
if (requestedType.isCompatibleWith(producibleType)) {
compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
}
}
}
if (compatibleMediaTypes.isEmpty()) {
if (returnValue != null) {
throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
}
return;
}
List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
MediaType.sortBySpecificityAndQuality(mediaTypes);
MediaType selectedMediaType = null;
for (MediaType mediaType : mediaTypes) {
if (mediaType.isConcrete()) {
selectedMediaType = mediaType;
break;
} else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
break;
}
}
if (selectedMediaType != null) {
selectedMediaType = selectedMediaType.removeQualityValue();
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType, returnValueClreplaced, selectedMediaType)) {
returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType, (Clreplaced<? extends HttpMessageConverter<?>>) messageConverter.getClreplaced(), inputMessage, outputMessage);
if (returnValue != null) {
addContentDispositionHeader(inputMessage, outputMessage);
((GenericHttpMessageConverter<T>) messageConverter).write(returnValue, returnValueType, selectedMediaType, outputMessage);
if (logger.isDebugEnabled()) {
logger.debug("Written [" + returnValue + "] as \"" + selectedMediaType + "\" using [" + messageConverter + "]");
}
}
return;
}
} else if (messageConverter.canWrite(returnValueClreplaced, selectedMediaType)) {
returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType, (Clreplaced<? extends HttpMessageConverter<?>>) messageConverter.getClreplaced(), inputMessage, outputMessage);
if (returnValue != null) {
addContentDispositionHeader(inputMessage, outputMessage);
((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType, outputMessage);
if (logger.isDebugEnabled()) {
logger.debug("Written [" + returnValue + "] as \"" + selectedMediaType + "\" using [" + messageConverter + "]");
}
}
return;
}
}
}
if (returnValue != null) {
throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
}
}
6
View Source File : ResourceHttpRequestHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Processes a resource request.
* <p>Checks for the existence of the requested resource in the configured list of locations.
* If the resource does not exist, a {@code 404} response will be returned to the client.
* If the resource exists, the request will be checked for the presence of the
* {@code Last-Modified} header, and its value will be compared against the last-modified
* timestamp of the given resource, returning a {@code 304} status code if the
* {@code Last-Modified} value is greater. If the resource is newer than the
* {@code Last-Modified} value, or the header is not present, the content resource
* of the resource will be written to the response with caching headers
* set to expire one year in the future.
*/
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// For very general mappings (e.g. "/") we need to check 404 first
Resource resource = getResource(request);
if (resource == null) {
logger.debug("Resource not found");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
response.setHeader("Allow", getAllowHeader());
return;
}
// Supported methods and required session
checkRequest(request);
// Header phase
if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
logger.trace("Resource not modified");
return;
}
// Apply cache settings, if any
prepareResponse(response);
// Check the media type for the resource
MediaType mediaType = getMediaType(request, resource);
// Content phase
if (METHOD_HEAD.equals(request.getMethod())) {
setHeaders(response, resource, mediaType);
return;
}
ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
if (request.getHeader(HttpHeaders.RANGE) == null) {
replacedert.state(this.resourceHttpMessageConverter != null, "Not initialized");
setHeaders(response, resource, mediaType);
this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
} else {
replacedert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
try {
List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
this.resourceRegionHttpMessageConverter.write(HttpRange.toResourceRegions(httpRanges, resource), mediaType, outputMessage);
} catch (IllegalArgumentException ex) {
response.setHeader("Content-Range", "bytes */" + resource.contentLength());
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
}
}
}
6
View Source File : AbstractMessageConverterMethodProcessor.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Writes the given return type to the given output message.
* @param value the value to write to the output message
* @param returnType the type of the value
* @param inputMessage the input messages. Used to inspect the {@code Accept} header.
* @param outputMessage the output message to write to
* @throws IOException thrown in case of I/O errors
* @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated
* by the {@code Accept} header on the request cannot be met by the message converters
* @throws HttpMessageNotWritableException thrown if a given message cannot
* be written by a converter, or if the content-type chosen by the server
* has no compatible converter.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
Object body;
Clreplaced<?> valueType;
Type targetType;
if (value instanceof CharSequence) {
body = value.toString();
valueType = String.clreplaced;
targetType = String.clreplaced;
} else {
body = value;
valueType = getReturnValueType(body, returnType);
targetType = GenericTypeResolver.resolveType(getGenericType(returnType), returnType.getContainingClreplaced());
}
if (isResourceType(value, returnType)) {
outputMessage.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
if (value != null && inputMessage.getHeaders().getFirst(HttpHeaders.RANGE) != null && outputMessage.getServletResponse().getStatus() == 200) {
Resource resource = (Resource) value;
try {
List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
outputMessage.getServletResponse().setStatus(HttpStatus.PARTIAL_CONTENT.value());
body = HttpRange.toResourceRegions(httpRanges, resource);
valueType = body.getClreplaced();
targetType = RESOURCE_REGION_LIST_TYPE;
} catch (IllegalArgumentException ex) {
outputMessage.getHeaders().set(HttpHeaders.CONTENT_RANGE, "bytes */" + resource.contentLength());
outputMessage.getServletResponse().setStatus(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value());
}
}
}
MediaType selectedMediaType = null;
MediaType contentType = outputMessage.getHeaders().getContentType();
boolean isContentTypePreset = contentType != null && contentType.isConcrete();
if (isContentTypePreset) {
if (logger.isDebugEnabled()) {
logger.debug("Found 'Content-Type:" + contentType + "' in response");
}
selectedMediaType = contentType;
} else {
HttpServletRequest request = inputMessage.getServletRequest();
List<MediaType> acceptableTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleTypes = getProducibleMediaTypes(request, valueType, targetType);
if (body != null && producibleTypes.isEmpty()) {
throw new HttpMessageNotWritableException("No converter found for return value of type: " + valueType);
}
List<MediaType> mediaTypesToUse = new ArrayList<>();
for (MediaType requestedType : acceptableTypes) {
for (MediaType producibleType : producibleTypes) {
if (requestedType.isCompatibleWith(producibleType)) {
mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
}
}
}
if (mediaTypesToUse.isEmpty()) {
if (body != null) {
throw new HttpMediaTypeNotAcceptableException(producibleTypes);
}
if (logger.isDebugEnabled()) {
logger.debug("No match for " + acceptableTypes + ", supported: " + producibleTypes);
}
return;
}
MediaType.sortBySpecificityAndQuality(mediaTypesToUse);
for (MediaType mediaType : mediaTypesToUse) {
if (mediaType.isConcrete()) {
selectedMediaType = mediaType;
break;
} else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
break;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using '" + selectedMediaType + "', given " + acceptableTypes + " and supported " + producibleTypes);
}
}
if (selectedMediaType != null) {
selectedMediaType = selectedMediaType.removeQualityValue();
for (HttpMessageConverter<?> converter : this.messageConverters) {
GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
if (genericConverter != null ? ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : converter.canWrite(valueType, selectedMediaType)) {
body = getAdvice().beforeBodyWrite(body, returnType, selectedMediaType, (Clreplaced<? extends HttpMessageConverter<?>>) converter.getClreplaced(), inputMessage, outputMessage);
if (body != null) {
Object theBody = body;
LogFormatUtils.traceDebug(logger, traceOn -> "Writing [" + LogFormatUtils.formatValue(theBody, !traceOn) + "]");
addContentDispositionHeader(inputMessage, outputMessage);
if (genericConverter != null) {
genericConverter.write(body, targetType, selectedMediaType, outputMessage);
} else {
((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Nothing to write: null body");
}
}
return;
}
}
}
if (body != null) {
Set<MediaType> producibleMediaTypes = (Set<MediaType>) inputMessage.getServletRequest().getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
if (isContentTypePreset || !CollectionUtils.isEmpty(producibleMediaTypes)) {
throw new HttpMessageNotWritableException("No converter for [" + valueType + "] with preset Content-Type '" + contentType + "'");
}
throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
}
}
1
View Source File : CommonController.java
License : Apache License 2.0
Project Creator : zhangdaiscott
License : Apache License 2.0
Project Creator : zhangdaiscott
/**
* 中转HTTP请求,解决跨域问题
*
* @param url 必填:请求地址
* @return
*/
@RequestMapping("/transitRESTful")
public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
try {
ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
// 中转请求method、body
HttpMethod method = httpRequest.getMethod();
JSONObject params;
try {
params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
} catch (Exception e) {
params = new JSONObject();
}
// 中转请求问号参数
JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
variables.remove("url");
// 在 headers 里传递Token
String token = TokenUtils.getTokenByRequest(request);
HttpHeaders headers = new HttpHeaders();
headers.set("X-Access-Token", token);
// 发送请求
String httpURL = URLDecoder.decode(url, "UTF-8");
ResponseEnreplacedy<String> response = RestUtil.request(httpURL, method, headers, variables, params, String.clreplaced);
// 封装返回结果
Result<Object> result = new Result<>();
int statusCode = response.getStatusCodeValue();
result.setCode(statusCode);
result.setSuccess(statusCode == 200);
String responseBody = response.getBody();
try {
// 尝试将返回结果转为JSON
Object json = JSON.parse(responseBody);
result.setResult(json);
} catch (Exception e) {
// 转成JSON失败,直接返回原始数据
result.setResult(responseBody);
}
return result;
} catch (Exception e) {
log.debug("中转HTTP请求失败", e);
return Result.error(e.getMessage());
}
}
0
View Source File : GlobalResponseHandler.java
License : Apache License 2.0
Project Creator : Xiao-Y
License : Apache License 2.0
Project Creator : Xiao-Y
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Clreplaced<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
log.info("请求的方法:{}", returnType.getMethod());
if (body == null) {
log.info("返回的类型:void");
} else {
log.info("返回的类型:{}", body.getClreplaced().getName());
}
ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
HttpServletRequest servletRequest = httpRequest.getServletRequest();
String requestURI = servletRequest.getRequestURI();
log.info("请求的方法URI:{}", requestURI);
// swagger2 ui
if (matcher.match("", requestURI) || matcher.match("/**/v3/api-docs", requestURI) || matcher.match("/**/swagger-resources", requestURI) || matcher.match("/**/swagger-resources/configuration/security", requestURI) || matcher.match("/**/swagger-resources/configuration/ui", requestURI)) {
return body;
}
BaseResponse baseResponse;
if (body instanceof BaseResponse) {
baseResponse = (BaseResponse) body;
} else if (body instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap<String, Object>) body;
ResCodeEnum resCode = (ResCodeEnum) map.get("resCode");
if (resCode == null) {
resCode = ResCodeEnum.RESCODE_OTHER_ERROR;
}
baseResponse = new BaseResponse(resCode);
baseResponse.setRequestUrl(map.get("path") + "");
} else if (body instanceof IPage) {
// mybatis 分页
IPage temp = (IPage) body;
CustomPage customPage = new CustomPage();
customPage.setTableData(temp.getRecords());
customPage.setRecordCount(temp.getTotal());
customPage.setTotalPages(temp.getPages());
baseResponse = BaseResponse.success(customPage);
} else if (body instanceof Page) {
// spring data jpa 分页
Page temp = (Page) body;
CustomPage customPage = new CustomPage();
customPage.setTableData(temp.getContent());
customPage.setRecordCount(temp.getTotalElements());
customPage.setTotalPages(temp.getTotalPages());
baseResponse = BaseResponse.success(customPage);
} else {
baseResponse = BaseResponse.success(body);
}
// baseResponse.setRequestUrl()
// log.info("\n响应参数:{} ", JSONObject.toJSONString(baseResponse));
// 处理返回值是String的情况
// if (body instanceof String) {
// return JSONObject.toJSONString(BaseResponse.success(body));
// }
return baseResponse;
}