Here are the examples of the java api org.springframework.web.server.ServerWebExchange taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1723 Examples
19
Source : WebFluxTags.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Creates a {@code status} tag based on the response status of the given
* {@code exchange}.
* @param exchange the exchange
* @return the status tag derived from the response status
*/
public static Tag status(ServerWebExchange exchange) {
HttpStatus status = exchange.getResponse().getStatusCode();
if (status == null) {
status = HttpStatus.OK;
}
return Tag.of("status", String.valueOf(status.value()));
}
19
Source : WebFluxTags.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Creates a {@code method} tag based on the
* {@link org.springframework.http.server.reactive.ServerHttpRequest#getMethod()
* method} of the {@link ServerWebExchange#getRequest()} request of the given
* {@code exchange}.
* @param exchange the exchange
* @return the method tag whose value is a capitalized method (e.g. GET).
*/
public static Tag method(ServerWebExchange exchange) {
return Tag.of("method", exchange.getRequest().getMethodValue());
}
19
Source : ResponseGatewayFilter.java
with MIT License
from xk11961677
with MIT License
from xk11961677
ServerHttpResponseDecorator responseDecorator(ServerWebExchange exchange) {
return new ServerHttpResponseDecorator(exchange.getResponse()) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
String originalResponseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, originalResponseContentType);
ResponseAdapter responseAdapter = new ResponseAdapter(body, httpHeaders);
CustomDefaultClientResponse clientResponse = new CustomDefaultClientResponse(responseAdapter, ExchangeStrategies.withDefaults(), "", "", () -> EMPTY_REQUEST);
Mono<String> rawBody = clientResponse.bodyToMono(String.clreplaced).map(s -> s);
BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(rawBody, String.clreplaced);
CustomCachedBodyOutputMessage outputMessage = new CustomCachedBodyOutputMessage(exchange, exchange.getResponse().getHeaders());
return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
Flux<DataBuffer> messageBody = outputMessage.getBody();
Flux<DataBuffer> flux = messageBody.map(buffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
DataBufferUtils.release(buffer);
// 将响应信息转化为字符串
String responseStr = charBuffer.toString();
LogUtils.info(log, "response parameters :{} ", responseStr);
return getDelegate().bufferFactory().wrap(responseStr.getBytes(StandardCharsets.UTF_8));
});
HttpHeaders headers = getDelegate().getHeaders();
// 修改响应包的大小,不修改会因为包大小不同被浏览器丢掉
flux = flux.doOnNext(data -> headers.setContentLength(data.readableByteCount()));
return getDelegate().writeWith(flux);
}));
}
};
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static FilterResult getFilterResult(ServerWebExchange exchange, String filter) {
return getFilterContext(exchange).get(filter);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Mono<Void> getDirectResponse(ServerWebExchange exchange) {
return (Mono<Void>) exchange.getAttributes().get(WebUtils.directResponse);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Mono<Void> responseError(ServerWebExchange exchange, int code, String msg) {
return responseError(exchange, null, code, msg, null, false);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Mono<Void> responseErrorAndBindContext(ServerWebExchange exchange, String filter, int code, String msg, Throwable t) {
return responseError(exchange, filter, code, msg, t, true);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static String appendQuery(String path, ServerWebExchange exchange) {
String qry = getClientReqQuery(exchange);
if (qry != null) {
return path + Constants.Symbol.QUESTION + qry;
}
return path;
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Object getFilterResultDataItem(ServerWebExchange exchange, String filter, String key) {
return getFilterResultData(exchange, filter).get(key);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Map<String, FilterResult> getFilterContext(ServerWebExchange exchange) {
return (Map<String, FilterResult>) exchange.getAttributes().get(FILTER_CONTEXT);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static FilterResult getPrevFilterResult(ServerWebExchange exchange) {
return getFilterContext(exchange).get(PREV_FILTER_RESULT);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Mono<Void> responseErrorAndBindContext(ServerWebExchange exchange, String filter, int code, String msg) {
return responseError(exchange, filter, code, msg, null, true);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Map<String, Object> getFilterResultData(ServerWebExchange exchange, String filter) {
return getFilterResult(exchange, filter).data;
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static String getClientReqPathQuery(ServerWebExchange exchange) {
String relativeUri = getClientReqPath(exchange);
String qry = getClientReqQuery(exchange);
if (qry != null) {
relativeUri = relativeUri + Constants.Symbol.QUESTION + qry;
}
return relativeUri;
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Mono<Void> responseError(ServerWebExchange exchange, String reporter, int code, String msg, Throwable t) {
return responseError(exchange, reporter, code, msg, t, false);
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static ApiConfig getApiConfig(ServerWebExchange exchange) {
Object authRes = getFilterResultDataItem(exchange, AuthPluginFilter.AUTH_PLUGIN_FILTER, AuthPluginFilter.RESULT);
if (authRes != null && authRes instanceof ApiConfig) {
return (ApiConfig) authRes;
} else {
return null;
}
}
19
Source : WebUtils.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public static Map<String, String> getAppendHeaders(ServerWebExchange exchange) {
return (Map<String, String>) exchange.getAttributes().get(APPEND_HEADERS);
}
19
Source : ApiConfigService.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
public Mono<Object> canAccess(ServerWebExchange exchange) {
ServerHttpRequest req = exchange.getRequest();
HttpHeaders hdrs = req.getHeaders();
LogService.setBizId(req.getId());
return canAccess(exchange, WebUtils.getAppId(exchange), WebUtils.getOriginIp(exchange), hdrs.getFirst(timestampHeader), hdrs.getFirst(signHeader), WebUtils.getClientService(exchange), req.getMethod(), WebUtils.getClientReqPath(exchange));
}
19
Source : PreprocessFilter.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
private Mono<Void> executeFixedPluginFilters(ServerWebExchange exchange) {
Mono vm = Mono.empty();
List<FixedPluginFilter> fixedPluginFilters = FixedPluginFilter.getPluginFilters();
for (byte i = 0; i < fixedPluginFilters.size(); i++) {
FixedPluginFilter fpf = fixedPluginFilters.get(i);
vm = vm.defaultIfEmpty(ReactorUtils.NULL).flatMap(v -> {
return fpf.filter(exchange, null, null);
});
}
return vm;
}
19
Source : CacheCheckController.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
@GetMapping("/resourceRateLimitConfigs")
public Mono<String> resourceRateLimitConfigs(ServerWebExchange exchange) {
return Mono.just(JacksonUtils.writeValuereplacedtring(resourceRateLimitConfigService.getResourceRateLimitConfigMap()));
}
19
Source : CacheCheckController.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
@GetMapping("/apiConfig2appsConfigs")
public Mono<String> apiConfig2appsConfigs(ServerWebExchange exchange) {
return Mono.just(JacksonUtils.writeValuereplacedtring(apiConifg2appsService.getApiConfig2appsMap()));
}
19
Source : CacheCheckController.java
with GNU General Public License v3.0
from wehotel
with GNU General Public License v3.0
from wehotel
@GetMapping("/currentGatewayGroups")
public Mono<String> currentGatewayGroups(ServerWebExchange exchange) {
return Mono.just(JacksonUtils.writeValuereplacedtring(gatewayGroupService.currentGatewayGroupSet));
}
19
Source : ExRetryGatewayFilterFactory.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
public boolean exceedsMaxIterations(ServerWebExchange exchange, RetryConfig retryConfig) {
Integer iteration = exchange.getAttribute(EX_RETRY_ITERATION_KEY);
boolean exceeds = iteration != null && iteration >= retryConfig.getRetries();
trace("exceedsMaxIterations %b, iteration %d, configured retries %d", exceeds, iteration, retryConfig.getRetries());
return exceeds;
}
19
Source : ViewResolutionResultHandlerTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void handleReturnValueTypes() {
Object returnValue;
MethodParameter returnType;
ViewResolver resolver = new TestViewResolver("account");
returnType = on(Handler.clreplaced).resolveReturnType(View.clreplaced);
returnValue = new TestView("account");
testHandle("/path", returnType, returnValue, "account: {id=123}");
returnType = on(Handler.clreplaced).resolveReturnType(Mono.clreplaced, View.clreplaced);
returnValue = Mono.just(new TestView("account"));
testHandle("/path", returnType, returnValue, "account: {id=123}");
returnType = on(Handler.clreplaced).annotNotPresent(ModelAttribute.clreplaced).resolveReturnType(String.clreplaced);
returnValue = "account";
testHandle("/path", returnType, returnValue, "account: {id=123}", resolver);
returnType = on(Handler.clreplaced).annotPresent(ModelAttribute.clreplaced).resolveReturnType(String.clreplaced);
returnValue = "123";
testHandle("/account", returnType, returnValue, "account: {id=123, myString=123}", resolver);
returnType = on(Handler.clreplaced).resolveReturnType(Mono.clreplaced, String.clreplaced);
returnValue = Mono.just("account");
testHandle("/path", returnType, returnValue, "account: {id=123}", resolver);
returnType = on(Handler.clreplaced).resolveReturnType(Model.clreplaced);
returnValue = new ConcurrentModel().addAttribute("name", "Joe").addAttribute("ignore", null);
testHandle("/account", returnType, returnValue, "account: {id=123, name=Joe}", resolver);
// Work around caching issue...
ResolvableType.clearCache();
returnType = on(Handler.clreplaced).annotNotPresent(ModelAttribute.clreplaced).resolveReturnType(Map.clreplaced);
returnValue = Collections.singletonMap("name", "Joe");
testHandle("/account", returnType, returnValue, "account: {id=123, name=Joe}", resolver);
// Work around caching issue...
ResolvableType.clearCache();
returnType = on(Handler.clreplaced).annotPresent(ModelAttribute.clreplaced).resolveReturnType(Map.clreplaced);
returnValue = Collections.singletonMap("name", "Joe");
testHandle("/account", returnType, returnValue, "account: {id=123, myMap={name=Joe}}", resolver);
returnType = on(Handler.clreplaced).resolveReturnType(TestBean.clreplaced);
returnValue = new TestBean("Joe");
String responseBody = "account: {id=123, " + "org.springframework.validation.BindingResult.testBean=" + "org.springframework.validation.BeanPropertyBindingResult: 0 errors, " + "testBean=TestBean[name=Joe]}";
testHandle("/account", returnType, returnValue, responseBody, resolver);
returnType = on(Handler.clreplaced).annotPresent(ModelAttribute.clreplaced).resolveReturnType(Long.clreplaced);
testHandle("/account", returnType, 99L, "account: {id=123, myLong=99}", resolver);
returnType = on(Handler.clreplaced).resolveReturnType(Rendering.clreplaced);
HttpStatus status = HttpStatus.UNPROCESSABLE_ENreplacedY;
returnValue = Rendering.view("account").modelAttribute("a", "a1").status(status).header("h", "h1").build();
String expected = "account: {a=a1, id=123}";
ServerWebExchange exchange = testHandle("/path", returnType, returnValue, expected, resolver);
replacedertEquals(status, exchange.getResponse().getStatusCode());
replacedertEquals("h1", exchange.getResponse().getHeaders().getFirst("h"));
}
19
Source : RequestMappingInfoHandlerMappingTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private void handleMatch(ServerWebExchange exchange, String pattern) {
RequestMappingInfo info = paths(pattern).build();
this.handlerMapping.handleMatch(info, handlerMethod, exchange);
}
19
Source : RequestPartMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void personNotRequired() {
MethodParameter param = this.testMethod.annot(requestPart().notRequired()).arg(Person.clreplaced);
ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
StepVerifier.create(result).verifyComplete();
}
19
Source : RequestPartMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void partRequired() {
MethodParameter param = this.testMethod.annot(requestPart()).arg(Part.clreplaced);
ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
StepVerifier.create(result).expectError(ServerWebInputException.clreplaced).verify();
}
19
Source : RequestPartMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void personRequired() {
MethodParameter param = this.testMethod.annot(requestPart()).arg(Person.clreplaced);
ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
StepVerifier.create(result).expectError(ServerWebInputException.clreplaced).verify();
}
19
Source : RequestPartMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void partNotRequired() {
MethodParameter param = this.testMethod.annot(requestPart().notRequired()).arg(Part.clreplaced);
ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
StepVerifier.create(result).verifyComplete();
}
19
Source : RequestParamMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private Object resolve(MethodParameter parameter, ServerWebExchange exchange) {
return this.resolver.resolveArgument(parameter, this.bindContext, exchange).block(Duration.ZERO);
}
19
Source : ModelInitializerTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Unit tests for {@link ModelInitializer}.
*
* @author Rossen Stoyanchev
*/
public clreplaced ModelInitializerTests {
private ModelInitializer modelInitializer;
private final ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path"));
@Before
public void setup() {
ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
ArgumentResolverConfigurer resolverConfigurer = new ArgumentResolverConfigurer();
resolverConfigurer.addCustomResolver(new ModelMethodArgumentResolver(adapterRegistry));
ControllerMethodResolver methodResolver = new ControllerMethodResolver(resolverConfigurer, adapterRegistry, new StaticApplicationContext(), Collections.emptyList());
this.modelInitializer = new ModelInitializer(methodResolver, adapterRegistry);
}
@Test
public void initBinderMethod() {
Validator validator = mock(Validator.clreplaced);
TestController controller = new TestController();
controller.setValidator(validator);
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(GetMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
WebExchangeDataBinder binder = context.createDataBinder(this.exchange, "name");
replacedertEquals(Collections.singletonList(validator), binder.getValidators());
}
@SuppressWarnings("unchecked")
@Test
public void modelAttributeMethods() {
TestController controller = new TestController();
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(GetMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
Map<String, Object> model = context.getModel().asMap();
replacedertEquals(5, model.size());
Object value = model.get("bean");
replacedertEquals("Bean", ((TestBean) value).getName());
value = model.get("monoBean");
replacedertEquals("Mono Bean", ((Mono<TestBean>) value).block(Duration.ofMillis(5000)).getName());
value = model.get("singleBean");
replacedertEquals("Single Bean", ((Single<TestBean>) value).toBlocking().value().getName());
value = model.get("voidMethodBean");
replacedertEquals("Void Method Bean", ((TestBean) value).getName());
value = model.get("voidMonoMethodBean");
replacedertEquals("Void Mono Method Bean", ((TestBean) value).getName());
}
@Test
public void saveModelAttributeToSession() {
TestController controller = new TestController();
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(GetMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
WebSession session = this.exchange.getSession().block(Duration.ZERO);
replacedertNotNull(session);
replacedertEquals(0, session.getAttributes().size());
context.saveModel();
replacedertEquals(1, session.getAttributes().size());
replacedertEquals("Bean", ((TestBean) session.getRequiredAttribute("bean")).getName());
}
@Test
public void retrieveModelAttributeFromSession() {
WebSession session = this.exchange.getSession().block(Duration.ZERO);
replacedertNotNull(session);
TestBean testBean = new TestBean("Session Bean");
session.getAttributes().put("bean", testBean);
TestController controller = new TestController();
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(GetMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
context.saveModel();
replacedertEquals(1, session.getAttributes().size());
replacedertEquals("Session Bean", ((TestBean) session.getRequiredAttribute("bean")).getName());
}
@Test
public void requiredSessionAttributeMissing() {
TestController controller = new TestController();
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(PostMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
try {
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
fail();
} catch (IllegalArgumentException ex) {
replacedertEquals("Required attribute 'missing-bean' is missing.", ex.getMessage());
}
}
@Test
public void clearModelAttributeFromSession() {
WebSession session = this.exchange.getSession().block(Duration.ZERO);
replacedertNotNull(session);
TestBean testBean = new TestBean("Session Bean");
session.getAttributes().put("bean", testBean);
TestController controller = new TestController();
InitBinderBindingContext context = getBindingContext(controller);
Method method = ResolvableMethod.on(TestController.clreplaced).annotPresent(GetMapping.clreplaced).resolveMethod();
HandlerMethod handlerMethod = new HandlerMethod(controller, method);
this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));
context.getSessionStatus().setComplete();
context.saveModel();
replacedertEquals(0, session.getAttributes().size());
}
private InitBinderBindingContext getBindingContext(Object controller) {
List<SyncInvocableHandlerMethod> binderMethods = MethodIntrospector.selectMethods(controller.getClreplaced(), BINDER_METHODS).stream().map(method -> new SyncInvocableHandlerMethod(controller, method)).collect(Collectors.toList());
WebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer();
return new InitBinderBindingContext(bindingInitializer, binderMethods);
}
@SuppressWarnings("unused")
@SessionAttributes({ "bean", "missing-bean" })
private static clreplaced TestController {
@Nullable
private Validator validator;
void setValidator(Validator validator) {
this.validator = validator;
}
@InitBinder
public void initDataBinder(WebDataBinder dataBinder) {
if (this.validator != null) {
dataBinder.addValidators(this.validator);
}
}
@ModelAttribute("bean")
public TestBean returnValue() {
return new TestBean("Bean");
}
@ModelAttribute("monoBean")
public Mono<TestBean> returnValueMono() {
return Mono.just(new TestBean("Mono Bean"));
}
@ModelAttribute("singleBean")
public Single<TestBean> returnValueSingle() {
return Single.just(new TestBean("Single Bean"));
}
@ModelAttribute
public void voidMethodBean(Model model) {
model.addAttribute("voidMethodBean", new TestBean("Void Method Bean"));
}
@ModelAttribute
public Mono<Void> voidMonoMethodBean(Model model) {
return Mono.just("Void Mono Method Bean").doOnNext(name -> model.addAttribute("voidMonoMethodBean", new TestBean(name))).then();
}
@GetMapping
public void handleGet() {
}
@PostMapping
public void handlePost(@ModelAttribute("missing-bean") TestBean testBean) {
}
}
private static clreplaced TestBean {
private final String name;
TestBean(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return "TestBean[name=" + this.name + "]";
}
}
private static final ReflectionUtils.MethodFilter BINDER_METHODS = method -> AnnotationUtils.findAnnotation(method, InitBinder.clreplaced) != null;
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithFluxBody() {
ServerWebExchange exchange = postExchange("line1\nline2\nline3\n");
ResolvableType type = httpEnreplacedyType(Flux.clreplaced, String.clreplaced);
HttpEnreplacedy<Flux<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
StepVerifier.create(httpEnreplacedy.getBody()).expectNext("line1").expectNext("line2").expectNext("line3").expectComplete().verify();
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithSingleBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(Single.clreplaced, String.clreplaced);
HttpEnreplacedy<Single<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody().toBlocking().value());
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithStringBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(String.clreplaced);
HttpEnreplacedy<String> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody());
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithRxJava2MaybeBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(Maybe.clreplaced, String.clreplaced);
HttpEnreplacedy<Maybe<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody().blockingGet());
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithCompletableFutureBody() throws Exception {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(CompletableFuture.clreplaced, String.clreplaced);
HttpEnreplacedy<CompletableFuture<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody().get());
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithRxJava2SingleBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(io.reactivex.Single.clreplaced, String.clreplaced);
HttpEnreplacedy<io.reactivex.Single<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody().blockingGet());
}
19
Source : HttpEntityMethodArgumentResolverTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void httpEnreplacedyWithMonoBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEnreplacedyType(Mono.clreplaced, String.clreplaced);
HttpEnreplacedy<Mono<String>> httpEnreplacedy = resolveValue(exchange, type);
replacedertEquals(exchange.getRequest().getHeaders(), httpEnreplacedy.getHeaders());
replacedertEquals("line1", httpEnreplacedy.getBody().block());
}
19
Source : HandshakeWebSocketService.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private Mono<Map<String, Object>> initAttributes(ServerWebExchange exchange) {
if (this.sessionAttributePredicate == null) {
return EMPTY_ATTRIBUTES;
}
return exchange.getSession().map(session -> session.getAttributes().entrySet().stream().filter(entry -> this.sessionAttributePredicate.test(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
19
Source : RedirectView.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Convert model to request parameters and redirect to the given URL.
*/
@Override
protected Mono<Void> renderInternal(Map<String, Object> model, @Nullable MediaType contentType, ServerWebExchange exchange) {
String targetUrl = createTargetUrl(model, exchange);
return sendRedirect(targetUrl, exchange);
}
19
Source : AbstractView.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Create a RequestContext to expose under the specified attribute name.
* <p>The default implementation creates a standard RequestContext instance
* for the given request and model. Can be overridden in subclreplacedes for
* custom instances.
* @param exchange current exchange
* @param model combined output Map (never {@code null}),
* with dynamic values taking precedence over static attributes
* @return the RequestContext instance
* @see #setRequestContextAttribute
*/
protected RequestContext createRequestContext(ServerWebExchange exchange, Map<String, Object> model) {
return new RequestContext(exchange, model, obtainApplicationContext(), getRequestDataValueProcessor());
}
19
Source : AbstractView.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Prepare the model to render.
* @param model a Map with name Strings as keys and corresponding model
* objects as values (Map can also be {@code null} in case of empty model)
* @param contentType the content type selected to render with which should
* match one of the {@link #getSupportedMediaTypes() supported media types}.
* @param exchange the current exchange
* @return {@code Mono} to represent when and if rendering succeeds
*/
@Override
public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType contentType, ServerWebExchange exchange) {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "View " + formatViewName() + ", model " + (model != null ? model : Collections.emptyMap()));
}
if (contentType != null) {
exchange.getResponse().getHeaders().setContentType(contentType);
}
return getModelAttributes(model, exchange).flatMap(mergedModel -> {
// Expose RequestContext?
if (this.requestContextAttribute != null) {
mergedModel.put(this.requestContextAttribute, createRequestContext(exchange, mergedModel));
}
return renderInternal(mergedModel, contentType, exchange);
});
}
19
Source : AbstractView.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Prepare the model to use for rendering.
* <p>The default implementation creates a combined output Map that includes
* model as well as static attributes with the former taking precedence.
*/
protected Mono<Map<String, Object>> getModelAttributes(@Nullable Map<String, ?> model, ServerWebExchange exchange) {
int size = (model != null ? model.size() : 0);
Map<String, Object> attributes = new LinkedHashMap<>(size);
if (model != null) {
attributes.putAll(model);
}
return resolveAsyncAttributes(attributes).then(Mono.just(attributes));
}
19
Source : RequestMappingInfoHandlerMapping.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Provide a Comparator to sort RequestMappingInfos matched to a request.
*/
@Override
protected Comparator<RequestMappingInfo> getMappingComparator(final ServerWebExchange exchange) {
return (info1, info2) -> info1.compareTo(info2, exchange);
}
19
Source : RequestMappingInfoHandlerMapping.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Check if the given RequestMappingInfo matches the current request and
* return a (potentially new) instance with conditions that match the
* current request -- for example with a subset of URL patterns.
* @return an info in case of a match; or {@code null} otherwise.
*/
@Override
protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, ServerWebExchange exchange) {
return info.getMatchingCondition(exchange);
}
19
Source : RequestMappingInfo.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Compares "this" info (i.e. the current instance) with another info in the context of a request.
* <p>Note: It is replacedumed both instances have been obtained via
* {@link #getMatchingCondition(ServerWebExchange)} to ensure they have conditions with
* content relevant to current request.
*/
@Override
public int compareTo(RequestMappingInfo other, ServerWebExchange exchange) {
int result = this.patternsCondition.compareTo(other.getPatternsCondition(), exchange);
if (result != 0) {
return result;
}
result = this.paramsCondition.compareTo(other.getParamsCondition(), exchange);
if (result != 0) {
return result;
}
result = this.headersCondition.compareTo(other.getHeadersCondition(), exchange);
if (result != 0) {
return result;
}
result = this.consumesCondition.compareTo(other.getConsumesCondition(), exchange);
if (result != 0) {
return result;
}
result = this.producesCondition.compareTo(other.getProducesCondition(), exchange);
if (result != 0) {
return result;
}
result = this.methodsCondition.compareTo(other.getMethodsCondition(), exchange);
if (result != 0) {
return result;
}
result = this.customConditionHolder.compareTo(other.customConditionHolder, exchange);
if (result != 0) {
return result;
}
return 0;
}
19
Source : InvocableHandlerMethod.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private void logArgumentErrorIfNecessary(ServerWebExchange exchange, MethodParameter parameter, Throwable ex) {
// Leave stack trace for later, if error is not handled...
String exMsg = ex.getMessage();
if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + formatArgumentError(parameter, exMsg));
}
}
}
19
Source : InvocableHandlerMethod.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private boolean isResponseHandled(Object[] args, ServerWebExchange exchange) {
if (getResponseStatus() != null || exchange.isNotModified()) {
return true;
}
for (Object arg : args) {
if (arg instanceof ServerHttpResponse || arg instanceof ServerWebExchange) {
return true;
}
}
return false;
}
19
Source : ModelInitializer.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Initialize the {@link org.springframework.ui.Model Model} based on a
* (type-level) {@code @SessionAttributes} annotation and
* {@code @ModelAttribute} methods.
* @param handlerMethod the target controller method
* @param bindingContext the context containing the model
* @param exchange the current exchange
* @return a {@code Mono} for when the model is populated.
*/
@SuppressWarnings("Convert2MethodRef")
public Mono<Void> initModel(HandlerMethod handlerMethod, InitBinderBindingContext bindingContext, ServerWebExchange exchange) {
List<InvocableHandlerMethod> modelMethods = this.methodResolver.getModelAttributeMethods(handlerMethod);
SessionAttributesHandler sessionAttributesHandler = this.methodResolver.getSessionAttributesHandler(handlerMethod);
if (!sessionAttributesHandler.hreplacedessionAttributes()) {
return invokeModelAttributeMethods(bindingContext, modelMethods, exchange);
}
return exchange.getSession().flatMap(session -> {
Map<String, Object> attributes = sessionAttributesHandler.retrieveAttributes(session);
bindingContext.getModel().mergeAttributes(attributes);
bindingContext.setSessionContext(sessionAttributesHandler, session);
return invokeModelAttributeMethods(bindingContext, modelMethods, exchange).doOnSuccess(aVoid -> findModelAttributes(handlerMethod, sessionAttributesHandler).forEach(name -> {
if (!bindingContext.getModel().containsAttribute(name)) {
Object value = session.getRequiredAttribute(name);
bindingContext.getModel().addAttribute(name, value);
}
}));
});
}
19
Source : AbstractMessageWriterResultHandler.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Write a given body to the response with {@link HttpMessageWriter}.
* @param body the object to write
* @param bodyParameter the {@link MethodParameter} of the body to write
* @param exchange the current exchange
* @return indicates completion or error
* @see #writeBody(Object, MethodParameter, MethodParameter, ServerWebExchange)
*/
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter, ServerWebExchange exchange) {
return this.writeBody(body, bodyParameter, null, exchange);
}
See More Examples