Java Code Examples for org.springframework.web.context.request.async.DeferredResult#setResult()
The following examples show how to use
org.springframework.web.context.request.async.DeferredResult#setResult() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PushService.java From es with Apache License 2.0 | 6 votes |
/** * 定期清空队列 防止中间推送消息时中断造成消息丢失 */ @Scheduled(fixedRate = 5L * 60 * 1000) public void sync() { Map<Long, Queue<DeferredResult<Object>>> oldMap = userIdToDeferredResultMap; userIdToDeferredResultMap = new ConcurrentHashMap<Long, Queue<DeferredResult<Object>>>(); for(Queue<DeferredResult<Object>> queue : oldMap.values()) { if(queue == null) { continue; } for(DeferredResult<Object> deferredResult : queue) { try { deferredResult.setResult(""); } catch (Exception e) { queue.remove(deferredResult); } } } }
Example 2
Source File: NotificationController.java From apollo with Apache License 2.0 | 5 votes |
@Override public void handleMessage(ReleaseMessage message, String channel) { logger.info("message received - channel: {}, message: {}", channel, message); String content = message.getMessage(); Tracer.logEvent("Apollo.LongPoll.Messages", content); if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) { return; } List<String> keys = STRING_SPLITTER.splitToList(content); //message should be appId+cluster+namespace if (keys.size() != 3) { logger.error("message format invalid - {}", content); return; } ResponseEntity<ApolloConfigNotification> notification = new ResponseEntity<>( new ApolloConfigNotification(keys.get(2), message.getId()), HttpStatus.OK); if (!deferredResults.containsKey(content)) { return; } //create a new list to avoid ConcurrentModificationException List<DeferredResult<ResponseEntity<ApolloConfigNotification>>> results = Lists.newArrayList(deferredResults.get(content)); logger.debug("Notify {} clients for key {}", results.size(), content); for (DeferredResult<ResponseEntity<ApolloConfigNotification>> result : results) { result.setResult(notification); } logger.debug("Notification completed"); }
Example 3
Source File: DeviceApiController.java From iotplatform with Apache License 2.0 | 5 votes |
@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 { String kafkaOutboundTopic = KafkaTopics.DEVICE_ATTRIBUTES_TOPIC; Device device = ctx.getDevice(); if (device != null && device.getId() != null) { // BasicToDeviceActorSessionMsg basicToDeviceActorSessionMsg = new // BasicToDeviceActorSessionMsg( // device, msg); JsonObject root = new JsonObject(); JsonElement jsonElement = new JsonParser().parse(json); root.add("d", jsonElement); root.addProperty("messageId", DEFAULT_REQUEST_ID); log.info("msg: {}", root.toString()); this.msgProducer.send(kafkaOutboundTopic, device.getId().toString(), root.toString()); responseWriter.setResult(new ResponseEntity<>(HttpStatus.OK)); } else { responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); } // 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 4
Source File: DeviceApiController.java From iotplatform with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/device/token/{deviceToken}/telemetry/shadow", method = RequestMethod.GET, produces = "application/json") public DeferredResult<ResponseEntity> getDeviceTelemetryShadow(@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<TsKvEntry> tsList = timeseriesService.findAllLatest(_deviceId).get(); // if (tsList != null) { // for (TsKvEntry tsKvEntry : tsList) { // String key = tsKvEntry.getKey(); // Object value = tsKvEntry.getValue(); // log.info("key:{}, value:{}", key, value); // } // } List<ThingsKVData> collect = tsList.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
Source File: XxlRpcRegistryServiceImpl.java From xxl-rpc with GNU General Public License v3.0 | 5 votes |
public String setFileRegistryData(XxlRpcRegistry xxlRpcRegistry){ // fileName String fileName = parseRegistryDataFileName(xxlRpcRegistry.getBiz(), xxlRpcRegistry.getEnv(), xxlRpcRegistry.getKey()); // valid repeat update Properties existProp = PropUtil.loadProp(fileName); if (existProp != null && existProp.getProperty("data").equals(xxlRpcRegistry.getData()) && existProp.getProperty("status").equals(String.valueOf(xxlRpcRegistry.getStatus())) ) { return new File(fileName).getPath(); } // write Properties prop = new Properties(); prop.setProperty("data", xxlRpcRegistry.getData()); prop.setProperty("status", String.valueOf(xxlRpcRegistry.getStatus())); PropUtil.writeProp(prop, fileName); logger.info(">>>>>>>>>>> xxl-rpc, setFileRegistryData: biz={}, env={}, key={}, data={}" , xxlRpcRegistry.getBiz(), xxlRpcRegistry.getEnv(), xxlRpcRegistry.getKey(), xxlRpcRegistry.getData()); // brocast monitor client List<DeferredResult> deferredResultList = registryDeferredResultMap.get(fileName); if (deferredResultList != null) { registryDeferredResultMap.remove(fileName); for (DeferredResult deferredResult: deferredResultList) { deferredResult.setResult(new ReturnT<>(ReturnT.SUCCESS_CODE, "Monitor key update.")); } } return new File(fileName).getPath(); }
Example 6
Source File: TestController.java From java-spring-web with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/asyncDeferred", method = RequestMethod.GET) public DeferredResult<ResponseEntity<String>> test() { verifyActiveSpan(); DeferredResult<ResponseEntity<String>> df = new DeferredResult<>(); df.setResult(ResponseEntity.status(202).body("deferred")); return df; }
Example 7
Source File: TraceFilterIntegrationTests.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@RequestMapping("/deferred") public DeferredResult<String> deferredMethod() { log.info("deferred"); span = this.tracer.currentSpan(); span.tag("tag", "value"); DeferredResult<String> result = new DeferredResult<>(); result.setResult("deferred"); return result; }
Example 8
Source File: PushService.java From es with Apache License 2.0 | 5 votes |
public void offline(final Long userId) { Queue<DeferredResult<Object>> queue = userIdToDeferredResultMap.remove(userId); if(queue != null) { for(DeferredResult<Object> result : queue) { try { result.setResult(""); } catch (Exception e) { //ignore } } } }
Example 9
Source File: XxlCommonRegistryServiceImpl.java From xxl-mq with GNU General Public License v3.0 | 5 votes |
public String setFileRegistryData(XxlCommonRegistry xxlCommonRegistry){ // fileName String fileName = parseRegistryDataFileName(xxlCommonRegistry.getKey()); // valid repeat update Properties existProp = PropUtil.loadProp(fileName); if (existProp != null && existProp.getProperty("data").equals(xxlCommonRegistry.getData()) ) { return new File(fileName).getPath(); } // write Properties prop = new Properties(); prop.setProperty("data", xxlCommonRegistry.getData()); PropUtil.writeProp(prop, fileName); logger.info(">>>>>>>>>>> xxl-mq, setFileRegistryData: key={}, data={}", xxlCommonRegistry.getKey(), xxlCommonRegistry.getData()); // brocast monitor client List<DeferredResult> deferredResultList = registryDeferredResultMap.get(fileName); if (deferredResultList != null) { registryDeferredResultMap.remove(fileName); for (DeferredResult deferredResult: deferredResultList) { deferredResult.setResult(new ReturnT<>(ReturnT.SUCCESS_CODE, "Monitor key update.")); } } return new File(fileName).getPath(); }
Example 10
Source File: AsyncTests.java From java-technology-stack with MIT License | 5 votes |
void onMessage(String name) { for (DeferredResult<Person> deferredResult : this.deferredResults) { deferredResult.setResult(new Person(name)); this.deferredResults.remove(deferredResult); } for (ListenableFutureTask<Person> futureTask : this.futureTasks) { futureTask.run(); this.futureTasks.remove(futureTask); } }
Example 11
Source File: HybridServiceTest.java From chassis with Apache License 2.0 | 5 votes |
@ActionMapping("getStuff") @RequestMapping(method={ RequestMethod.GET }, value="/") public DeferredResult<TestObject> getStuff() { DeferredResult<TestObject> result = new DeferredResult<TestObject>(); result.setResult(stuff.get()); return result; }
Example 12
Source File: DeviceApiController.java From IOT-Technical-Guide with Apache License 2.0 | 5 votes |
private boolean quotaExceeded(HttpServletRequest request, DeferredResult<ResponseEntity> responseWriter) { if (quotaService.isQuotaExceeded(request.getRemoteAddr())) { log.warn("REST Quota exceeded for [{}] . Disconnect", request.getRemoteAddr()); responseWriter.setResult(new ResponseEntity<>(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)); return true; } return false; }
Example 13
Source File: DeviceApiController.java From IOT-Technical-Guide with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/attributes",method = RequestMethod.POST) public DeferredResult<ResponseEntity> postDeviceAttributes( @RequestBody String json, HttpServletRequest request) { DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>(); if (quotaExceeded(request, responseWriter)) { return responseWriter; } responseWriter.setResult(new ResponseEntity<>(HttpStatus.ACCEPTED)); Set<AttributeKvEntry> attributeKvEntrySet = JsonConverter.convertToAttributes(new JsonParser().parse(json)).getAttributes(); for (AttributeKvEntry attributeKvEntry : attributeKvEntrySet){ System.out.println("属性名="+attributeKvEntry.getKey()+" 属性值="+attributeKvEntry.getValueAsString()); } return responseWriter; }
Example 14
Source File: AsyncTests.java From spring-analysis-note with MIT License | 5 votes |
void onMessage(String name) { for (DeferredResult<Person> deferredResult : this.deferredResults) { deferredResult.setResult(new Person(name)); this.deferredResults.remove(deferredResult); } for (ListenableFutureTask<Person> futureTask : this.futureTasks) { futureTask.run(); this.futureTasks.remove(futureTask); } }
Example 15
Source File: XxlConfNodeServiceImpl.java From xxl-conf with GNU General Public License v3.0 | 4 votes |
@Override public DeferredResult<ReturnT<String>> monitor(String accessToken, String env, List<String> keys) { // init DeferredResult deferredResult = new DeferredResult(confBeatTime * 1000L, new ReturnT<>(ReturnT.SUCCESS_CODE, "Monitor timeout, no key updated.")); // valid if (this.accessToken!=null && this.accessToken.trim().length()>0 && !this.accessToken.equals(accessToken)) { deferredResult.setResult(new ReturnT<>(ReturnT.FAIL.getCode(), "AccessToken Invalid.")); return deferredResult; } if (env==null || env.trim().length()==0) { deferredResult.setResult(new ReturnT<>(ReturnT.FAIL.getCode(), "env Invalid.")); return deferredResult; } if (keys==null || keys.size()==0) { deferredResult.setResult(new ReturnT<>(ReturnT.FAIL.getCode(), "keys Invalid.")); return deferredResult; } /*for (String key: keys) { if (key==null || key.trim().length()<4 || key.trim().length()>100) { deferredResult.setResult(new ReturnT<>(ReturnT.FAIL.getCode(), "Key Invalid[4~100]")); return deferredResult; } if (!RegexUtil.matches(RegexUtil.abc_number_line_point_pattern, key)) { deferredResult.setResult(new ReturnT<>(ReturnT.FAIL.getCode(), "Key format Invalid")); return deferredResult; } }*/ // monitor by client for (String key: keys) { // invalid key, pass if (key==null || key.trim().length()<4 || key.trim().length()>100 || !RegexUtil.matches(RegexUtil.abc_number_line_point_pattern, key) ) { continue; } // monitor each key String fileName = parseConfDataFileName(env, key); List<DeferredResult> deferredResultList = confDeferredResultMap.get(fileName); if (deferredResultList == null) { deferredResultList = new ArrayList<>(); confDeferredResultMap.put(fileName, deferredResultList); } deferredResultList.add(deferredResult); } return deferredResult; }
Example 16
Source File: ClientAppNotifyController.java From radar with Apache License 2.0 | 4 votes |
@PostMapping("/getAppPolling") public DeferredResult<GetAppResponse> getServicePolling(@RequestBody GetAppRequest request) { GetAppResponse response = new GetAppResponse(); response.setSuc(true); response.setSleepTime(RandomUtils.nextInt(50,2000)); request.setInTime(System.currentTimeMillis()); DeferredResult<GetAppResponse> deferredResult = new DeferredResult<>(TIMEOUT, response); GetAppResponse getApplicationResponse = doCheckServPolling(request); if (getApplicationResponse != null) { if (soaConfig.isFullLog()) { getFollowMsg(request, "getServicePolling direct end notify"); } deferredResult.setResult(getApplicationResponse); } else { mapAppPolling.put(request, deferredResult); if (soaConfig.isFullLog()) { getFollowMsg(request, "getServicePolling wait notify"); } long count = longPollingCounter.incrementAndGet(); TraceMessageItem traceMessageItem = new TraceMessageItem(); traceMessageItem.status = count + ""; if (count > soaConfig.getPollingSize()) { if (soaConfig.isFullLog()) { getFollowMsg(request, "getServicePolling exce size notify"); } response.setSleepTime(RandomUtils.nextInt(50,2000)); deferredResult.setResult(response); longPollingCounter.decrementAndGet(); } else { deferredResult.onTimeout(() -> { getFollowMsg(request, "getServicePolling time out notify"); logWatchedKeysToCat(request, "infrastructure.LongPoll.TimeOutKeys"); }); deferredResult.onCompletion(() -> { Transaction transaction = Tracer.newTransaction("Service", "getServicePolling"); try { if (mapAppPolling.remove(request) != null) { if (soaConfig.isFullLog()) { getFollowMsg(request, "getServicePolling finished notify"); } long count1 = longPollingCounter.decrementAndGet(); traceMessageItem.msg = count + "_" + count1; traceMessageItem.end(); traceMessage3.add(traceMessageItem); logWatchedKeysToCat(request, "infrastructure.LongPoll.CompletionKeys"); } transaction.setStatus(Transaction.SUCCESS); } catch (Exception e) { transaction.setStatus(e); } finally { transaction.complete(); } }); } } return deferredResult; }
Example 17
Source File: ConsumerGroupNotifyController.java From pmq with Apache License 2.0 | 4 votes |
@PostMapping("/getConsumerGroupPolling") public DeferredResult<GetConsumerGroupResponse> getConsumerGroupPolling( @RequestBody GetConsumerGroupRequest request) { GetConsumerGroupResponse response = new GetConsumerGroupResponse(); response.setSuc(true); response.setSleepTime(RandomUtils.nextInt(50, 2000)); response.setBrokerMetaMode(soaConfig.getBrokerMetaMode()); DeferredResult<GetConsumerGroupResponse> deferredResult = new DeferredResult<>( soaConfig.getPollingTimeOut() * 1000L, response); GetConsumerGroupResponse getApplicationResponse = doCheckConsumerGroupPolling(request); if (getApplicationResponse != null) { deferredResult.setResult(getApplicationResponse); } else { mapAppPolling.put(request, deferredResult); long count = longPollingCounter.incrementAndGet(); TraceMessageItem traceMessageItem = new TraceMessageItem(); traceMessageItem.status = count + ""; if (count > soaConfig.getPollingSize()) { response.setSleepTime(RandomUtils.nextInt(50, 2000)); deferredResult.setResult(response); longPollingCounter.decrementAndGet(); } else { deferredResult.onTimeout(() -> { getFollowMsg(request, "getConsumerGroupPolling time out notify"); }); deferredResult.onCompletion(() -> { Transaction transaction = Tracer.newTransaction("Service", "getConsumerGroupPolling"); try { if (mapAppPolling.remove(request) != null) { long count1 = longPollingCounter.decrementAndGet(); traceMessageItem.msg = count + "_" + count1; traceMessage3.add(traceMessageItem); } transaction.setStatus(Transaction.SUCCESS); } catch (Exception e) { transaction.setStatus(e); } finally { transaction.complete(); } }); } } return deferredResult; }
Example 18
Source File: DeviceApiController.java From iotplatform with Apache License 2.0 | 4 votes |
@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, @RequestParam(value = "serverKeys", required = false, defaultValue = "") String serverKeys) { 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<>(); if (StringUtils.isEmpty(clientKeys) && StringUtils.isEmpty(sharedKeys) && StringUtils.isEmpty(serverKeys)) { Arrays.asList(DataConstants.ALL_SCOPES) .forEach(attributeType -> futures.add(attributesService.findAll(_deviceId, attributeType))); } else { Set<String> clientKeySet = !StringUtils.isEmpty(clientKeys) ? new HashSet<>(Arrays.asList(clientKeys.split(","))) : new HashSet<>(); Set<String> sharedKeySet = !StringUtils.isEmpty(sharedKeys) ? new HashSet<>(Arrays.asList(sharedKeys.split(","))) : new HashSet<>(); Set<String> serverKeySet = !StringUtils.isEmpty(serverKeys) ? new HashSet<>(Arrays.asList(serverKeys.split(","))) : new HashSet<>(); clientKeySet.addAll(sharedKeySet); clientKeySet.addAll(serverKeySet); Arrays.asList(DataConstants.ALL_SCOPES) .forEach(attributeType -> futures.add(attributesService.find(_deviceId, attributeType, clientKeySet))); } 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)); } // 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 19
Source File: WebSocketTransportTest.java From chassis with Apache License 2.0 | 4 votes |
@ActionMapping("getStuff") public DeferredResult<TestObject> getStuff() { DeferredResult<TestObject> result = new DeferredResult<TestObject>(); result.setResult(stuff.get()); return result; }
Example 20
Source File: WebSocketAction.java From chassis with Apache License 2.0 | 4 votes |
/** * Invokes this action. * * @param handler * @param message * @param envelope * @param session * @return * @throws MethodArgumentNotValidException * * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException */ public DeferredResult<?> invoke(Object handler, RawWebSocketMessage<?> message, WebSocketEnvelope envelope, WebSocketSession session) throws Exception { Object response = null; // invoke the method Object[] parameters = new Object[method.getParameterTypes().length]; Integer payloadParamIndex = parameterTypes.get(ParameterType.ACTION_PAYLOAD); if (payloadParamIndex != null) { parameters[payloadParamIndex] = message.deserialize(this); } Integer sessionParamIndex = parameterTypes.get(ParameterType.WEB_SOCKET_SESSION); if (sessionParamIndex != null) { parameters[sessionParamIndex] = session; } Integer transactionParamIndex = parameterTypes.get(ParameterType.TRANSACTION_ID); if (transactionParamIndex != null) { parameters[transactionParamIndex] = envelope.getTransactionId(); } Integer envelopeParamIndex = parameterTypes.get(ParameterType.ENVELOPE); if (envelopeParamIndex != null) { parameters[envelopeParamIndex] = envelope; } resolveCustomArguments(parameters, method, session, envelope); // now do actual invoke response = method.invoke(handler, parameters); // otherwise there was no error if (response != null) { // find a converter for (WebSocketResponseConverter converter : responseConverters.get()) { if (converter.canConvertResponse(response)) { return converter.convertToDeferredResult(response); } } // default to using the object as is final DeferredResult<Object> deferredResult = new DeferredResult<>(); deferredResult.setResult(response); return deferredResult; } else { return null; } }