Java Code Examples for org.springframework.web.context.request.async.DeferredResult

The following are top voted examples for showing how to use org.springframework.web.context.request.async.DeferredResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-boot-oauth2-demo   File: SpringfoxConfig.java   View source code 7 votes vote down vote up
@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"));
}
 
Example 2
Project: ReactiveTest   File: SpringTobyTv009Application.java   View source code 6 votes vote down vote up
@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;
}
 
Example 3
Project: ReactiveTest   File: SpringTobyTv010Application.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: iothub   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: spring-backend-boilerplate   File: SpringfoxConfiguration.java   View source code 6 votes vote down vote up
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);
}
 
Example 6
Project: spring-cloud-docker-microservice-book-code   File: AggregationController.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: grpc-java-contrib   File: GuavaLFReturnValueHandler.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: grpc-java-contrib   File: GuavaLFReturnValueHandlerTest.java   View source code 6 votes vote down vote up
@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");
}
 
Example 9
Project: grpc-java-contrib   File: GuavaLFReturnValueHandlerTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 10
Project: spring-boot-oauth2-demo   File: SpringfoxConfig.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 11
Project: apollo-custom   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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");
}
 
Example 12
Project: apollo-custom   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 13
Project: apollo-custom   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 14
Project: apollo-custom   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 15
Project: apollo-custom   File: NotificationControllerV2Test.java   View source code 6 votes vote down vote up
@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);
}
 
Example 16
Project: iotplatform   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 17
Project: iotplatform   File: PluginApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 18
Project: wiredtigervsvmap   File: DeferredResultAdapter.java   View source code 6 votes vote down vote up
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;
}
 
Example 19
Project: thingsboard   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 20
Project: whatsmars   File: SwaggerConfig.java   View source code 6 votes vote down vote up
@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());
    }
 
Example 21
Project: apollo   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 22
Project: apollo   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 23
Project: apollo   File: NotificationControllerTest.java   View source code 6 votes vote down vote up
@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));
  }
}
 
Example 24
Project: thingsboard   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 25
Project: paradox-nakadi-consumer   File: ControllerConfiguration.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: thingsboard   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 27
Project: thingsboard   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 28
Project: spring4-understanding   File: ListenableFutureReturnValueHandler.java   View source code 6 votes vote down vote up
@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);
		}
	});
}
 
Example 29
Project: spring4-understanding   File: AsyncTests.java   View source code 6 votes vote down vote up
@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;
}
 
Example 30
Project: spring-boot-concourse   File: MetricFilterAutoConfigurationTests.java   View source code 6 votes vote down vote up
@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;
}
 
Example 31
Project: thingsboard   File: DeviceApiController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 32
Project: interview-preparation   File: ApiDocumentationConfig.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 33
Project: interview-preparation   File: ApiDocumentationConfig.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 34
Project: fiware-openlpwa-iotagent   File: AgentRestController.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 35
Project: fiware-openlpwa-iotagent   File: AgentRestControllerTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 36
Project: spring-boot-concourse   File: MetricFilterAutoConfigurationTests.java   View source code 6 votes vote down vote up
@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;
}
 
Example 37
Project: micro-ecommerce   File: Application.java   View source code 6 votes vote down vote up
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;
}
 
Example 38
Project: esup-nfc-tag-server   File: ErrorLongPoolController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 39
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: MetricFilterAutoConfigurationTests.java   View source code 6 votes vote down vote up
@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;
}
 
Example 40
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: MetricFilterAutoConfigurationTests.java   View source code 6 votes vote down vote up
@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;
}