@GetMapping(value="/webSyncDept/{id}.json", produces ="application/json", headers = {"Accept=text/xml, application/json"}) public WebAsyncTask<Department> websyncDeptList(@PathVariable("id") Integer id){ Callable<Department> callable = new Callable<Department>() { public Department call() throws Exception { ListenableFuture<Department> listenFuture = departmentServiceImpl.findAllFirstById(id); listenFuture.addCallback(new ListenableFutureCallback<Department>(){ @Override public void onSuccess(Department dept) { result = dept; } @Override public void onFailure(Throwable arg0) { result = new Department(); } }); return result; } }; return new WebAsyncTask<Department>(500, callable); }
@RequestMapping(value="/web/webasync.html") @ResponseBody public WebAsyncTask<String> longTimeTask(){ Callable<String> callable = new Callable<String>() { public String call() throws Exception { Thread.sleep(3000); System.out.println("controller#webasync task started. Thread: " + Thread.currentThread() .getName()); return "Trial"; } }; return new WebAsyncTask<String>(callable); }
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()") public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp) throws Throwable { final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) pjp.proceed(); if (this.tracer.isTracing()) { try { log.debug("Wrapping callable with span [" + this.tracer.getCurrentSpan() + "]"); Field callableField = WebAsyncTask.class.getDeclaredField("callable"); callableField.setAccessible(true); callableField.set(webAsyncTask, new TraceContinuingCallable<>(this.tracer, this.spanNamer, webAsyncTask.getCallable())); } catch (NoSuchFieldException ex) { log.warn("Cannot wrap webAsyncTask's callable with TraceCallable", ex); } } return webAsyncTask; }
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()") public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp) throws Throwable { final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) pjp.proceed(); if (this.tracer.isTracing()) { try { if (log.isDebugEnabled()) { log.debug("Wrapping callable with span [" + this.tracer.getCurrentSpan() + "]"); } Field callableField = WebAsyncTask.class.getDeclaredField("callable"); callableField.setAccessible(true); callableField.set(webAsyncTask, new SpanContinuingTraceCallable<>(this.tracer, this.traceKeys, this.spanNamer, webAsyncTask.getCallable())); } catch (NoSuchFieldException ex) { log.warn("Cannot wrap webAsyncTask's callable with TraceCallable", ex); } } return webAsyncTask; }
@RequestMapping(value="/web/webasync.html") public WebAsyncTask<String> longTimeTask(){ Callable<String> callable = new Callable<String>() { public String call() throws Exception { Thread.sleep(3000); logger.info("controller#longTimeTask task started."); System.out.println("controller#webasync task started. Thread: " + Thread.currentThread() .getName()); return "Tral"; } }; return new WebAsyncTask<String>(callable); }
@RequestMapping(value="/web/employeeList.json", produces ="application/json", method = RequestMethod.GET, headers = {"Accept=text/xml, application/json"}) @ResponseBody public WebAsyncTask<List<Employee>> jsonEmpList(){ Callable<List<Employee>> callable = new Callable<List<Employee>>() { public List<Employee> call() throws Exception { Thread.sleep(3000); logger.info("ServiceController#jsonEmpList task started."); System.out.println("jsonEmpList task executor: " + Thread.currentThread().getName()); return employeeServiceImpl.readEmployees().get(50000, TimeUnit.MILLISECONDS); } }; return new WebAsyncTask<List<Employee>>(5000, callable); }
@RequestMapping(value="/web/employeeList.json", produces ="application/json", method = RequestMethod.GET, headers = {"Accept=text/xml, application/json"}) @ResponseBody public WebAsyncTask<List<Employee>> jsonEmpList(){ Callable<List<Employee>> callable = new Callable<List<Employee>>() { public List<Employee> call() throws Exception { Thread.sleep(3000); System.out.println("jsonEmpList task executor: " + Thread.currentThread().getName()); return employeeServiceImpl.readEmployees().get(5000, TimeUnit.MILLISECONDS); } }; return new WebAsyncTask<List<Employee>>(5000, callable); }
@GetMapping(value="/webSyncDeptList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"}) public WebAsyncTask<List<Department>> websyncDeptList(){ Callable<List<Department>> callable = new Callable<List<Department>>() { public List<Department> call() throws Exception { return departmentServiceImpl.readDepartments().get(500, TimeUnit.MILLISECONDS); } }; return new WebAsyncTask<List<Department>>(500, callable); }
@GetMapping(value="/webSyncEmpList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"}) public WebAsyncTask<List<Employee>> websyncEmpList(){ Callable<List<Employee>> callable = new Callable<List<Employee>>() { public List<Employee> call() throws Exception { return employeeServiceImpl.readEmployees().get(500, TimeUnit.MILLISECONDS); } }; return new WebAsyncTask<List<Employee>>(500, callable); }
/** * Handle request. * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @RequestMapping(method = RequestMethod.GET) @ResponseBody protected WebAsyncTask<HealthStatus> handleRequestInternal( final HttpServletRequest request, final HttpServletResponse response) throws Exception { final Callable<HealthStatus> asyncTask = new Callable<HealthStatus>() { @Override public HealthStatus call() throws Exception { final HealthStatus healthStatus = healthCheckMonitor.observe(); final StringBuilder sb = new StringBuilder(); sb.append("Health: ").append(healthStatus.getCode()); String name; Status status; int i = 0; for (final Map.Entry<String, Status> entry : healthStatus.getDetails().entrySet()) { name = entry.getKey(); status = entry.getValue(); response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription())); sb.append("\n\n\t").append(++i).append('.').append(name).append(": "); sb.append(status.getCode()); if (status.getDescription() != null) { sb.append(" - ").append(status.getDescription()); } } response.setStatus(healthStatus.getCode().value()); response.setContentType("text/plain"); response.getOutputStream().write(sb.toString().getBytes(response.getCharacterEncoding())); return null; } }; return new WebAsyncTask<>(this.timeout, asyncTask); }
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()") public Object tracePublicWebAsyncTaskMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) proceedingJoinPoint.proceed(); Field callableField = WebAsyncTask.class.getDeclaredField("callable"); callableField.setAccessible(true); // do not create span (there is always server span) just pass it to new thread. callableField .set(webAsyncTask, new TracedCallable<>(webAsyncTask.getCallable(), tracer.activeSpan())); return webAsyncTask; }
@RequestMapping("/webAsyncTask") public WebAsyncTask<String> webAsyncTask() { return new WebAsyncTask<>(() -> { mockTracer.buildSpan("foo").startManual().finish(); return "webAsyncTask"; }); }
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue; webAsyncTask.setBeanFactory(this.beanFactory); WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer); }
@RequestMapping(value = "/webAsyncTaskPing", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE) public WebAsyncTask<String> webAsyncTaskPing() { return new WebAsyncTask<>(new Callable<String>() { @Override public String call() throws Exception { return callAndReturnOk(); } }); }
@RequestMapping(value = "/media/music/add", method = RequestMethod.POST) public WebAsyncTask<Void> addMovie(Model model, MultipartFile musicFile, MusicDto musicDto) { log.info("用户[" + UserUtils.getCurrentUserId() + "]正在上传音乐" + ToStringBuilder.reflectionToString(musicDto)); return new WebAsyncTask<>(fileUploadTime, new MusicAsyncCallable(model, musicFile, musicDto, filePath, musicService)); }
/** * 异步处理文件上传,Servlet3规范新特性,不会消耗更多的资源 * * @param model * @param movieFile * @param movieDto * @param madeDate * @param request * @return */ @RequestMapping(value = "/media/movie/add", method = RequestMethod.POST) public WebAsyncTask<Void> addMovie(Model model, MultipartFile movieFile, MovieDto movieDto, @DateTimeFormat(pattern = "yyyy-MM-dd") Date madeDate, HttpServletRequest request) { log.info("用户[" + UserUtils.getCurrentUserId() + "]正在上传视频[标题:"+movieDto.getTitle()+"]"); return new WebAsyncTask<Void>(fileUploadTime, new MovieAsyncCallable(model, movieFile, movieDto, madeDate, movieService, filePath)); }
/** * [SLEUTH] WebAsyncTask */ @RequestMapping(value = "/{ingredient}", method = RequestMethod.POST) public WebAsyncTask<Ingredient> ingredients(@PathVariable("ingredient") IngredientType ingredientType, @RequestHeader("PROCESS-ID") String processId, @RequestHeader(TestConfigurationHolder.TEST_COMMUNICATION_TYPE_HEADER_NAME) String testCommunicationType) { log.info("Received a request to [/{}] with process id [{}] and communication type [{}]", ingredientType, processId, testCommunicationType); return new WebAsyncTask<>(() -> { Span span = tracer.createSpan("inside_ingredients"); Ingredient ingredient = new Ingredient(ingredientType, stubbedIngredientsProperties.getReturnedIngredientsQuantity()); log.info("Returning [{}] as fetched ingredient from an external service", ingredient); tracer.close(span); return ingredient; }); }
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue; webAsyncTask.setBeanFactory(this.beanFactory); WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer); }
@RequestMapping(value = "/feignAsyncList", method = RequestMethod.GET, produces = "application/json") public WebAsyncTask<List<Department>> allAsyncDepts() { WebAsyncTask<List<Department>> depts = deptListClient.getAsyncListDepts(); return depts; }
@RequestMapping(method = RequestMethod.GET, value = "/webSyncDeptList.json" ) public WebAsyncTask<List<Department>> getAsyncListDepts();
/** * Handle request. * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @GetMapping @ResponseBody protected WebAsyncTask<HealthStatus> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { ensureEndpointAccessIsAuthorized(request, response); final Callable<HealthStatus> asyncTask = () -> { final HealthStatus healthStatus = healthCheckMonitor.observe(); response.setStatus(healthStatus.getCode().value()); if (StringUtils.equals(request.getParameter("format"), "json")) { response.setContentType(MediaType.APPLICATION_JSON_VALUE); JsonUtils.render(healthStatus.getDetails(), response); } else { final StringBuilder sb = new StringBuilder(); sb.append("Health: ").append(healthStatus.getCode()); final AtomicInteger i = new AtomicInteger(); healthStatus.getDetails().forEach((name, status) -> { response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription())); sb.append("\n\n\t").append(i.incrementAndGet()).append('.').append(name).append(": "); sb.append(status.getCode()); if (status.getDescription() != null) { sb.append(" - ").append(status.getDescription()); } }); sb.append("\n\nHost:\t\t").append( StringUtils.isBlank(casProperties.getHost().getName()) ? InetAddressUtils.getCasServerHostName() : casProperties.getHost().getName() ); sb.append("\nServer:\t\t").append(casProperties.getServer().getName()); sb.append("\nVersion:\t").append(CasVersion.getVersion()); response.setContentType(MediaType.TEXT_PLAIN_VALUE); try (Writer writer = response.getWriter()) { IOUtils.copy(new ByteArrayInputStream(sb.toString().getBytes(response.getCharacterEncoding())), writer, StandardCharsets.UTF_8); writer.flush(); } } return null; }; return new WebAsyncTask<>(casProperties.getHttpClient().getAsyncTimeout(), asyncTask); }
@Override public boolean supportsReturnType(MethodParameter returnType) { return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType()); }
@Override public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { return (returnValue != null && returnValue instanceof WebAsyncTask); }
@Override public boolean supports(EndpointMethod endpointMethod) { return endpointMethod.returnType().is(WebAsyncTask.class); }
@Override public EndpointCallExecutable<WebAsyncTask<T>, O> create(EndpointMethod endpointMethod, EndpointCallExecutable<T, O> executable) { return new WebAsyncTaskEndpointCallExecutable(executable); }
@Override public WebAsyncTask<T> execute(EndpointCall<O> call, Object[] args) { return new WebAsyncTask<T>(timeout, asyncTaskExecutor, () -> delegate.execute(call, args)); }
@Test public void shouldCreateExecutableFromEndpointMethodWithWebAsyncTaskReturnType() throws Exception { EndpointCallExecutable<WebAsyncTask<String>, String> executable = factory .create(new SimpleEndpointMethod(SomeType.class.getMethod("webAsyncTask")), delegate); String result = "future result"; WebAsyncTask<String> future = executable.execute(() -> result, null); assertNotNull(future); assertEquals(result, future.getCallable().call()); assertEquals(delegate.returnType(), executable.returnType()); verify(delegate).execute(any(), anyVararg()); }
@SuppressWarnings("rawtypes") WebAsyncTask dumbWebAsyncTask();
public boolean supportsReturnType(MethodParameter returnType) { Class<?> paramType = returnType.getParameterType(); return WebAsyncTask.class.isAssignableFrom(paramType); }
WebAsyncTask<String> webAsyncTask();