本文整理汇总了Java中org.springframework.web.context.request.async.DeferredResult类的典型用法代码示例。如果您正苦于以下问题:Java DeferredResult类的具体用法?Java DeferredResult怎么用?Java DeferredResult使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DeferredResult类属于org.springframework.web.context.request.async包,在下文中一共展示了DeferredResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: practiceApi
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Bean
public Docket practiceApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.sdcuike.practice"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(
newRule(typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder()
.code(500)
.message("500 message")
.responseModel(new ModelRef("Error"))
.build()))
.enableUrlTemplating(true)
.tags(new Tag("Pet Service", "All apis relating to pets"));
}
示例2: rest
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@GetMapping("/rest")
public DeferredResult<String> rest(int idx) {
DeferredResult<String> dr = new DeferredResult<String>();
ListenableFuture<ResponseEntity<String>> f1 = rt.getForEntity(URL1, String.class, "h" + idx);
f1.addCallback(s -> {
ListenableFuture<ResponseEntity<String>> f2 = rt.getForEntity(URL2, String.class, s.getBody());
f2.addCallback(s2 -> {
ListenableFuture<String> f3 = myService.work(s2.getBody());
f3.addCallback(s3 -> {
dr.setResult(s3);
}, e3 -> {
dr.setErrorResult(e3.getMessage());
});
}, e2 -> {
dr.setErrorResult(e2.getMessage());
});
}, e -> {
dr.setErrorResult(e.getMessage());
});
return dr;
}
示例3: getDeviceAttributesShadow
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@RequestMapping(value = "/device/token/{deviceToken}/attributes/shadow", method = RequestMethod.GET, produces = "application/json")
public DeferredResult<ResponseEntity> getDeviceAttributesShadow(@PathVariable("deviceToken") String deviceToken) {
DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
DeviceId _deviceId = ctx.getDevice().getId();
try {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
Arrays.asList(DataConstants.ALL_SCOPES)
.forEach(attributeType -> futures.add(attributesService.findAll(_deviceId, attributeType)));
ListenableFuture<List<List<AttributeKvEntry>>> successfulAsList = Futures.successfulAsList(futures);
List<AttributeKvEntry> result = new ArrayList<>();
successfulAsList.get().forEach(r -> result.addAll(r));
List<ThingsKVData> collect = result.stream().map(attribute -> new ThingsKVData(attribute.getKey(), attribute.getValue())).collect(Collectors.toList());
responseWriter.setResult(new ResponseEntity<>(collect, HttpStatus.OK));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
} else {
responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
}
return responseWriter;
}
示例4: api
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(AlternateTypeRules.newRule(typeResolver.resolve(
DeferredResult.class,
typeResolver.resolve(ResponseEntity.class,
WildcardType.class)),
typeResolver.resolve(
WildcardType.class)))
.useDefaultResponseMessages(false);
}
示例5: toDeferredResult
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
public DeferredResult<HashMap<String, User>> toDeferredResult(Observable<HashMap<String, User>> details) {
DeferredResult<HashMap<String, User>> result = new DeferredResult<>();
// 订阅
details.subscribe(new Observer<HashMap<String, User>>() {
@Override
public void onCompleted() {
LOGGER.info("完成...");
}
@Override
public void onError(Throwable throwable) {
LOGGER.error("发生错误...", throwable);
}
@Override
public void onNext(HashMap<String, User> movieDetails) {
result.setResult(movieDetails);
}
});
return result;
}
开发者ID:itmuch,项目名称:spring-cloud-docker-microservice-book-code,代码行数:22,代码来源:AggregationController.java
示例6: handleReturnValue
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
final DeferredResult<Object> deferredResult = new DeferredResult<>();
@SuppressWarnings("unchecked")
ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue;
Futures.addCallback(futureValue, new FutureCallback<Object>() {
@Override
public void onSuccess(@Nullable Object result) {
deferredResult.setResult(result);
}
@Override
public void onFailure(Throwable ex) {
deferredResult.setErrorResult(ex);
}
});
startDeferredResultProcessing(mavContainer, webRequest, deferredResult);
}
示例7: handlesSuccess
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void handlesSuccess() throws Exception {
final AtomicReference<Object> value = new AtomicReference<>();
ListenableFuture<String> future = Futures.immediateFuture("42");
GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() {
@Override
protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception {
value.set(deferredResult.getResult());
}
};
handler.handleReturnValue(future, null, null, null);
assertThat(value.get()).isEqualTo("42");
}
示例8: handlesFailure
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void handlesFailure() throws Exception {
final AtomicReference<Object> value = new AtomicReference<>();
Exception ex = new Exception("This is bad");
ListenableFuture<String> future = Futures.immediateFailedFuture(ex);
GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() {
@Override
protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception {
value.set(deferredResult.getResult());
}
};
handler.handleReturnValue(future, null, null, null);
assertThat(value.get()).isEqualTo(ex);
}
示例9: setUp
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
controller = new NotificationController();
ReflectionTestUtils.setField(controller, "releaseMessageService", releaseMessageService);
ReflectionTestUtils.setField(controller, "entityManagerUtil", entityManagerUtil);
ReflectionTestUtils.setField(controller, "namespaceUtil", namespaceUtil);
ReflectionTestUtils.setField(controller, "watchKeysUtil", watchKeysUtil);
someAppId = "someAppId";
someCluster = "someCluster";
defaultCluster = ConfigConsts.CLUSTER_NAME_DEFAULT;
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
somePublicNamespace = "somePublicNamespace";
someDataCenter = "someDC";
someNotificationId = 1;
someClientIp = "someClientIp";
when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);
when(namespaceUtil.filterNamespaceName(somePublicNamespace)).thenReturn(somePublicNamespace);
deferredResults =
(Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
.getField(controller, "deferredResults");
}
示例10: testPollNotificationWithDefaultNamespace
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void testPollNotificationWithDefaultNamespace() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
示例11: testPollNotificationWithDefaultNamespaceAsFile
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void testPollNotificationWithDefaultNamespaceAsFile() throws Exception {
String namespace = String.format("%s.%s", defaultNamespace, "properties");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(defaultNamespace);
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
示例12: testPollNotificationWithSomeNamespaceAsFile
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void testPollNotificationWithSomeNamespaceAsFile() throws Exception {
String namespace = String.format("someNamespace.xml");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(namespace);
String someWatchKey = "someKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, namespace, someDataCenter))
.thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
示例13: testPollNotificationWithDefaultNamespace
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@Test
public void testPollNotificationWithDefaultNamespace() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Multimap<String, String> watchKeysMap =
assembleMultiMap(defaultNamespace, Lists.newArrayList(someWatchKey, anotherWatchKey));
String notificationAsString =
transformApolloConfigNotificationsToString(defaultNamespace, someNotificationId);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, Sets.newHashSet(defaultNamespace),
someDataCenter)).thenReturn(
watchKeysMap);
DeferredResult<ResponseEntity<List<ApolloConfigNotification>>>
deferredResult = controller
.pollNotification(someAppId, someCluster, notificationAsString, someDataCenter,
someClientIp);
assertEquals(watchKeysMap.size(), deferredResults.size());
assertWatchKeys(watchKeysMap, deferredResult);
}
示例14: processRequest
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/{pluginToken}/**")
@ResponseStatus(value = HttpStatus.OK)
public DeferredResult<ResponseEntity> processRequest(
@PathVariable("pluginToken") String pluginToken,
RequestEntity<byte[]> requestEntity,
HttpServletRequest request)
throws IoTPException {
log.debug("[{}] Going to process requst uri: {}", pluginToken, requestEntity.getUrl());
DeferredResult<ResponseEntity> result = new DeferredResult<ResponseEntity>();
PluginMetaData pluginMd = pluginService.findPluginByApiToken(pluginToken);
if (pluginMd == null) {
result.setErrorResult(new PluginNotFoundException("Plugin with token: " + pluginToken + " not found!"));
} else {
TenantId tenantId = getCurrentUser().getTenantId();
CustomerId customerId = getCurrentUser().getCustomerId();
if (validatePluginAccess(pluginMd, tenantId, customerId)) {
if(ModelConstants.NULL_UUID.equals(tenantId.getId())){
tenantId = null;
}
PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId);
actorService.process(new BasicPluginRestMsg(securityCtx, new RestRequest(requestEntity, request), result));
} else {
result.setResult(new ResponseEntity<>(HttpStatus.FORBIDDEN));
}
}
return result;
}
示例15: requestAsync
import org.springframework.web.context.request.async.DeferredResult; //导入依赖的package包/类
public static <T> DeferredResult<T> requestAsync(final TaskExecutor executor,
final Callable<T> action) {
final DeferredResult<T> result = new DeferredResult<>();
final Runnable beforeCallable = () -> {
try {
T t = action.call();
if (result.isSetOrExpired()) {
log.error("async request expired");
return;
}
result.setResult(t);
} catch (final Exception ex) {
result.setErrorResult(ex);
}
};
executor.execute(beforeCallable);
return result;
}