當前位置: 首頁>>代碼示例>>Java>>正文


Java DeferredResult類代碼示例

本文整理匯總了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"));
}
 
開發者ID:sdcuike,項目名稱:spring-boot-oauth2-demo,代碼行數:25,代碼來源:SpringfoxConfig.java

示例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;
}
 
開發者ID:sejoung,項目名稱:ReactiveTest,代碼行數:24,代碼來源:SpringTobyTv009Application.java

示例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;
}
 
開發者ID:osswangxining,項目名稱:iothub,代碼行數:27,代碼來源:DeviceApiController.java

示例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);
}
 
開發者ID:melthaw,項目名稱:spring-backend-boilerplate,代碼行數:19,代碼來源:SpringfoxConfiguration.java

示例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);
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:26,代碼來源:GuavaLFReturnValueHandler.java

示例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");
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:17,代碼來源:GuavaLFReturnValueHandlerTest.java

示例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);
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:17,代碼來源:GuavaLFReturnValueHandlerTest.java

示例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");
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:25,代碼來源:NotificationControllerTest.java

示例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));
  }
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:24,代碼來源:NotificationControllerTest.java

示例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));
  }
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:27,代碼來源:NotificationControllerTest.java

示例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));
  }
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:26,代碼來源:NotificationControllerTest.java

示例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);
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:26,代碼來源:NotificationControllerV2Test.java

示例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;
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:31,代碼來源:PluginApiController.java

示例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;
}
 
開發者ID:rsdomingues,項目名稱:wiredtigervsvmap,代碼行數:23,代碼來源:DeferredResultAdapter.java


注:本文中的org.springframework.web.context.request.async.DeferredResult類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。