Java 类org.springframework.web.context.request.async.DeferredResult 实例源码

项目:ReactiveTest    文件:SpringTobyTv009Application.java   
@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;
}
项目:ReactiveTest    文件:SpringTobyTv010Application.java   
@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;
}
项目:iothub    文件:DeviceApiController.java   
@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;
}
项目:spring-backend-boilerplate    文件:SpringfoxConfiguration.java   
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);
}
项目:spring-cloud-docker-microservice-book-code    文件:AggregationController.java   
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;
}
项目:grpc-java-contrib    文件:GuavaLFReturnValueHandler.java   
@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);
}
项目:grpc-java-contrib    文件:GuavaLFReturnValueHandlerTest.java   
@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");
}
项目:grpc-java-contrib    文件:GuavaLFReturnValueHandlerTest.java   
@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);
}
项目:spring-boot-oauth2-demo    文件:SpringfoxConfig.java   
@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"));
}
项目:spring-boot-oauth2-demo    文件:SpringfoxConfig.java   
@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"));
}
项目:apollo-custom    文件:NotificationControllerTest.java   
@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");
}
项目:apollo-custom    文件:NotificationControllerTest.java   
@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));
  }
}
项目:apollo-custom    文件:NotificationControllerTest.java   
@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));
  }
}
项目:apollo-custom    文件:NotificationControllerTest.java   
@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));
  }
}
项目:apollo-custom    文件:NotificationControllerV2Test.java   
@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);
}
项目:iotplatform    文件:DeviceApiController.java   
@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;
}
项目:iotplatform    文件:PluginApiController.java   
@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;
}
项目:wiredtigervsvmap    文件:DeferredResultAdapter.java   
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;
}
项目:thingsboard    文件:DeviceApiController.java   
@RequestMapping(value = "/{deviceToken}/rpc/{requestId}", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> replyToCommand(@PathVariable("deviceToken") String deviceToken,
                                                     @PathVariable("requestId") Integer requestId,
                                                     @RequestBody String json) {
    DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
    HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
    if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
        try {
            JsonObject response = new JsonParser().parse(json).getAsJsonObject();
            process(ctx, new ToDeviceRpcResponseMsg(requestId, response.toString()));
        } catch (IllegalStateException | JsonSyntaxException ex) {
            responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        }
    } else {
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
    }
    return responseWriter;
}
项目:whatsmars    文件:SwaggerConfig.java   
@Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("business-api")
                .select()
                .apis(RequestHandlerSelectors.basePackage(App.class.getPackage().getName()))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .genericModelSubstitutes(ResponseEntity.class)
                .alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class)))
//                .enableUrlTemplating(true)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .host(host())
                .apiInfo(apiInfo());
    }
项目:apollo    文件:NotificationControllerTest.java   
@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));
  }
}
项目:apollo    文件:NotificationControllerTest.java   
@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));
  }
}
项目:apollo    文件:NotificationControllerTest.java   
@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));
  }
}
项目:thingsboard    文件:DeviceApiController.java   
@RequestMapping(value = "/{deviceToken}/attributes", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> postDeviceAttributes(@PathVariable("deviceToken") String deviceToken,
                                                           @RequestBody String json) {
    DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
    HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
    if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
        try {
            process(ctx, JsonConverter.convertToAttributes(new JsonParser().parse(json)));
        } catch (IllegalStateException | JsonSyntaxException ex) {
            responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        }
    } else {
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
    }
    return responseWriter;
}
项目:paradox-nakadi-consumer    文件:ControllerConfiguration.java   
private DeferredResult<ResponseEntity<?>> deferredReplayResult(final EventTypePartition eventTypePartition,
        final String consumerName, final boolean verbose, final Single<String> singleContent) {

    final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(DEFERRED_TIMEOUT);
    final Set<EventTypeConsumer> consumers = registry.getEventTypeConsumers().stream()
                                                     .filter(filterConsumer(eventTypePartition.getName(),
                consumerName)).collect(Collectors.toSet());
    if (consumers.isEmpty()) {
        deferredResult.setErrorResult(ResponseEntity.notFound().build());
    } else {
        singleContent.subscribe(content -> {
                consumers.forEach(eventTypeConsumer -> {
                    final EventHandler<?> handler = requireNonNull(
                            registry.getEventTypeConsumerHandler(eventTypeConsumer), "handler not found");
                    replayHandler.handle(consumerName, handler, eventTypePartition, content);
                });
                deferredResult.setResult(ok(verbose ? content : ""));

            },
            throwable -> deferredResult.setErrorResult(badRequest().body(throwable.toString())));
    }

    return deferredResult;
}
项目:thingsboard    文件:DeviceApiController.java   
@RequestMapping(value = "/{deviceToken}/attributes", method = RequestMethod.GET, produces = "application/json")
public DeferredResult<ResponseEntity> getDeviceAttributes(@PathVariable("deviceToken") String deviceToken,
                                                          @RequestParam(value = "clientKeys", required = false, defaultValue = "") String clientKeys,
                                                          @RequestParam(value = "sharedKeys", required = false, defaultValue = "") String sharedKeys) {
    DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
    HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
    if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
        GetAttributesRequest request;
        if (StringUtils.isEmpty(clientKeys) && StringUtils.isEmpty(sharedKeys)) {
            request = new BasicGetAttributesRequest(0);
        } else {
            Set<String> clientKeySet = !StringUtils.isEmpty(clientKeys) ? new HashSet<>(Arrays.asList(clientKeys.split(","))) : null;
            Set<String> sharedKeySet = !StringUtils.isEmpty(sharedKeys) ? new HashSet<>(Arrays.asList(sharedKeys.split(","))) : null;
            request = new BasicGetAttributesRequest(0, clientKeySet, sharedKeySet);
        }
        process(ctx, request);
    } else {
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
    }

    return responseWriter;
}
项目:thingsboard    文件:DeviceApiController.java   
@RequestMapping(value = "/{deviceToken}/rpc", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> postRpcRequest(@PathVariable("deviceToken") String deviceToken,
                                                     @RequestBody String json) {
    DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
    HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
    if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
        try {
            JsonObject request = new JsonParser().parse(json).getAsJsonObject();
            process(ctx, new ToServerRpcRequestMsg(0,
                    request.get("method").getAsString(),
                    request.get("params").toString()));
        } catch (IllegalStateException | JsonSyntaxException ex) {
            responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        }
    } else {
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
    }
    return responseWriter;
}
项目:spring4-understanding    文件:ListenableFutureReturnValueHandler.java   
@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<Object>();
    WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

    ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
    future.addCallback(new ListenableFutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            deferredResult.setResult(result);
        }
        @Override
        public void onFailure(Throwable ex) {
            deferredResult.setErrorResult(ex);
        }
    });
}
项目:spring4-understanding    文件:AsyncTests.java   
@RequestMapping(params = "deferredResultWithDelayedError")
public DeferredResult<Person> getDeferredResultWithDelayedError() {
    final DeferredResult<Person> deferredResult = new DeferredResult<Person>();
    new Thread() {
        public void run() {
            try {
                Thread.sleep(100);
                deferredResult.setErrorResult(new RuntimeException("Delayed Error"));
            }
            catch (InterruptedException e) {
                /* no-op */
            }
        }
    }.start();
    return deferredResult;
}
项目:spring-boot-concourse    文件:MetricFilterAutoConfigurationTests.java   
@RequestMapping("create")
public DeferredResult<ResponseEntity<String>> create() {
    final DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MetricFilterTestController.this.latch.await();
                result.setResult(
                        new ResponseEntity<String>("Done", HttpStatus.CREATED));
            }
            catch (InterruptedException ex) {
            }
        }
    }).start();
    return result;
}
项目:thingsboard    文件:DeviceApiController.java   
@RequestMapping(value = "/{deviceToken}/telemetry", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> postTelemetry(@PathVariable("deviceToken") String deviceToken,
                                                    @RequestBody String json) {
    DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
    HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
    if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
        try {
            process(ctx, JsonConverter.convertToTelemetry(new JsonParser().parse(json)));
        } catch (IllegalStateException | JsonSyntaxException ex) {
            responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        }
    } else {
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
    }
    return responseWriter;
}
项目:interview-preparation    文件:ApiDocumentationConfig.java   
@Bean
public Docket petApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            // .apis(RequestHandlerSelectors.any())
            .apis(RequestHandlerSelectors.basePackage("com.tvajjala.resource"))
            .paths(PathSelectors.any())
            // .paths(PathSelectors.ant("/api/*"))
            .build()
            .apiInfo(apiInfo())
            .pathMapping("/api")
            // .directModelSubstitute(LocalDate.class, String.class)
            .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()))
            .securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()));
}
项目:interview-preparation    文件:ApiDocumentationConfig.java   
@Bean
public Docket petApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            // .apis(RequestHandlerSelectors.any())
            .apis(RequestHandlerSelectors.basePackage("com.tvajjala.web.resource"))
            .paths(PathSelectors.any())
            // .paths(PathSelectors.ant("/api/*"))
            .build()
            .apiInfo(apiInfo())
            .pathMapping("/api")
            // .directModelSubstitute(LocalDate.class, String.class)
            .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()))
            .securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()));
}
项目:fiware-openlpwa-iotagent    文件:AgentRestController.java   
/**
 * Unregister a device
 * @param deviceEUI Device EUI of the device to unregister
 * @return A <code>DeferredResult</code> which contains the response
 */
@RequestMapping(method = RequestMethod.DELETE,
        value = "/devices/{deviceEUI}")
final public DeferredResult<ResponseEntity<?>> unregister(@PathVariable String deviceEUI) {
    final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();

    agent.unregister(deviceEUI,
            () -> {
                logger.debug("Device correctly unregistered ({})", deviceEUI);
                deferredResult.setResult(ResponseEntity.noContent().build());
            },
            ex -> {
                logger.error("Device not unregistered ({})", deviceEUI, ex);
                deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex));
            });
    return deferredResult;
}
项目:fiware-openlpwa-iotagent    文件:AgentRestControllerTest.java   
@Test
public void testRegisterSuccess() {
    Device device = new Device();
    device.setDeviceEUI("123");
    device.setEntityType("type");
    device.setEntityName("name");
    device.setPort(1);

    simulateAgentRegisterSuccess();

    DeferredResult<ResponseEntity<?>> deferredResult = agentRestController.register(device);
    verify(mockAgent, times(1)).register(eq(device), any(AgentSuccessCallback.class), any(AgentFailureCallback.class));
    ResponseEntity<?> entity = (ResponseEntity<?>) deferredResult.getResult();
    assertEquals(HttpStatus.CREATED, entity.getStatusCode());
    assertEquals(String.format("/devices/%s", device.getDeviceEUI()), entity.getHeaders().get("Location").get(0));
}
项目:spring-boot-concourse    文件:MetricFilterAutoConfigurationTests.java   
@RequestMapping("createFailure")
public DeferredResult<ResponseEntity<String>> createFailure() {
    final DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MetricFilterTestController.this.latch.await();
                result.setErrorResult(new Exception("It failed"));
            }
            catch (InterruptedException ex) {

            }
        }
    }).start();
    return result;
}
项目:micro-ecommerce    文件:Application.java   
public DeferredResult<ProductDetails> toDeferredResult(Observable<ProductDetails> details) {
    DeferredResult<ProductDetails> result = new DeferredResult<>();
    details.subscribe(new Observer<ProductDetails>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable throwable) {
        }

        @Override
        public void onNext(ProductDetails productDetails) {
            result.setResult(productDetails);
        }
    });
    return result;
}
项目:esup-nfc-tag-server    文件:ErrorLongPoolController.java   
@RequestMapping(value = "/tagerror")
@ResponseBody
public DeferredResult<List<TagError>> tagError(@RequestParam Long errorDateTimestamp, @RequestParam(required=false) String numeroId) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if(numeroId==null && !auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN")) && !auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_SUPERVISOR"))) {
        return null;
    }
    LiveQuery liveQuery = new LiveQuery(errorDateTimestamp, numeroId);
    final DeferredResult<List<TagError>> tagErrors = new DeferredResult<List<TagError>>(null, Collections.emptyList());

    this.suspendedTagErrorsRequests.put(tagErrors, liveQuery);

    tagErrors.onCompletion(new Runnable() {
        public void run() {
            suspendedTagErrorsRequests.remove(tagErrors);
        }
    });

    return tagErrors;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MetricFilterAutoConfigurationTests.java   
@RequestMapping("create")
public DeferredResult<ResponseEntity<String>> create() {
    final DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MetricFilterTestController.this.latch.await();
                result.setResult(
                        new ResponseEntity<String>("Done", HttpStatus.CREATED));
            }
            catch (InterruptedException ex) {
            }
        }
    }).start();
    return result;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MetricFilterAutoConfigurationTests.java   
@RequestMapping("createFailure")
public DeferredResult<ResponseEntity<String>> createFailure() {
    final DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MetricFilterTestController.this.latch.await();
                result.setErrorResult(new Exception("It failed"));
            }
            catch (InterruptedException ex) {

            }
        }
    }).start();
    return result;
}