@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; }
@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; }
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); }
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; }
@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); }
@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"); }
@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); }
@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")); }
@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"); }
@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)); } }
@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)); } }
@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)); } }
@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); }
@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; }
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; }
@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; }
@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()); }
@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; }
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; }
@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; }
@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; }
@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); } }); }
@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; }
@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; }
@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; }
@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())); }
@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())); }
/** * 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; }
@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)); }
@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; }
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; }
@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; }