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

The following are top voted examples for showing how to use org.springframework.web.context.request.async.WebAsyncTask. 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-5.0-Cookbook   File: DataController.java   View source code 7 votes vote down vote up
@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);
}
 
Example 2
Project: Spring-5.0-Cookbook   File: DeptAsyncController.java   View source code 6 votes vote down vote up
@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);
}
 
Example 3
Project: Zipkin   File: TraceWebAspect.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: spring-cloud-sleuth   File: TraceWebAspect.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: Spring-5.0-Cookbook   File: DataController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 6
Project: Spring-5.0-Cookbook   File: ServiceController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 7
Project: Spring-5.0-Cookbook   File: ServiceController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 8
Project: Spring-5.0-Cookbook   File: DeptAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 9
Project: Spring-5.0-Cookbook   File: EmpAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 10
Project: Spring-5.0-Cookbook   File: DeptAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 11
Project: Spring-5.0-Cookbook   File: EmpAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 12
Project: Spring-5.0-Cookbook   File: DeptAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 13
Project: Spring-5.0-Cookbook   File: DataController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 14
Project: Spring-5.0-Cookbook   File: ServiceController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 15
Project: Spring-5.0-Cookbook   File: EmpAsyncController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 16
Project: springboot-shiro-cas-mybatis   File: HealthCheckController.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 17
Project: java-spring-cloud   File: TracedAsyncWebAspect.java   View source code 5 votes vote down vote up
@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;
}
 
Example 18
Project: java-spring-cloud   File: WebAsyncTaskTest.java   View source code 5 votes vote down vote up
@RequestMapping("/webAsyncTask")
public WebAsyncTask<String> webAsyncTask() {
  return new WebAsyncTask<>(() -> {
    mockTracer.buildSpan("foo").startManual().finish();
    return "webAsyncTask";
  });
}
 
Example 19
Project: spring4-understanding   File: AsyncTaskMethodReturnValueHandler.java   View source code 5 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;
	}

	WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
	webAsyncTask.setBeanFactory(this.beanFactory);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
}
 
Example 20
Project: Zipkin   File: RestTemplateTraceAspectIntegrationTests.java   View source code 5 votes vote down vote up
@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();
		}
	});
}
 
Example 21
Project: MultimediaDesktop   File: MusicController.java   View source code 5 votes vote down vote up
@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));
}
 
Example 22
Project: MultimediaDesktop   File: MovieController.java   View source code 5 votes vote down vote up
/**
 * 异步处理文件上传,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));
}
 
Example 23
Project: brewery   File: IngredientsFetchController.java   View source code 5 votes vote down vote up
/**
 * [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;
	});
}
 
Example 24
Project: spring-cloud-sleuth   File: RestTemplateTraceAspectIntegrationTests.java   View source code 5 votes vote down vote up
@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();
		}
	});
}
 
Example 25
Project: class-guard   File: AsyncTaskMethodReturnValueHandler.java   View source code 5 votes vote down vote up
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);
}
 
Example 26
Project: Spring-5.0-Cookbook   File: DeptFeignController.java   View source code 4 votes vote down vote up
@RequestMapping(value = "/feignAsyncList", method = RequestMethod.GET, produces = "application/json")
  public WebAsyncTask<List<Department>> allAsyncDepts()			    {
WebAsyncTask<List<Department>> depts = deptListClient.getAsyncListDepts();
return depts;
    }
 
Example 27
Project: Spring-5.0-Cookbook   File: DeptListClient.java   View source code 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/webSyncDeptList.json" )
public WebAsyncTask<List<Department>> getAsyncListDepts();
 
Example 28
Project: cas-5.1.0   File: HealthCheckController.java   View source code 4 votes vote down vote up
/**
 * 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);
}
 
Example 29
Project: spring4-understanding   File: AsyncTaskMethodReturnValueHandler.java   View source code 4 votes vote down vote up
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
}
 
Example 30
Project: spring4-understanding   File: AsyncTaskMethodReturnValueHandler.java   View source code 4 votes vote down vote up
@Override
public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
	return (returnValue != null && returnValue instanceof WebAsyncTask);
}
 
Example 31
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactory.java   View source code 4 votes vote down vote up
@Override
public boolean supports(EndpointMethod endpointMethod) {
	return endpointMethod.returnType().is(WebAsyncTask.class);
}
 
Example 32
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactory.java   View source code 4 votes vote down vote up
@Override
public EndpointCallExecutable<WebAsyncTask<T>, O> create(EndpointMethod endpointMethod, EndpointCallExecutable<T, O> executable) {
	return new WebAsyncTaskEndpointCallExecutable(executable);
}
 
Example 33
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactory.java   View source code 4 votes vote down vote up
@Override
public WebAsyncTask<T> execute(EndpointCall<O> call, Object[] args) {
	return new WebAsyncTask<T>(timeout, asyncTaskExecutor, () -> delegate.execute(call, args));
}
 
Example 34
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactoryTest.java   View source code 4 votes vote down vote up
@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());
}
 
Example 35
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactoryTest.java   View source code 4 votes vote down vote up
@SuppressWarnings("rawtypes")
WebAsyncTask dumbWebAsyncTask();
 
Example 36
Project: class-guard   File: AsyncTaskMethodReturnValueHandler.java   View source code 4 votes vote down vote up
public boolean supportsReturnType(MethodParameter returnType) {
	Class<?> paramType = returnType.getParameterType();
	return WebAsyncTask.class.isAssignableFrom(paramType);
}
 
Example 37
Project: java-restify   File: WebAsyncTaskEndpointCallExecutableFactoryTest.java   View source code votes vote down vote up
WebAsyncTask<String> webAsyncTask();