当前位置: 首页>>代码示例>>Java>>正文


Java AsyncContext类代码示例

本文整理汇总了Java中javax.servlet.AsyncContext的典型用法代码示例。如果您正苦于以下问题:Java AsyncContext类的具体用法?Java AsyncContext怎么用?Java AsyncContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


AsyncContext类属于javax.servlet包,在下文中一共展示了AsyncContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doGet

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Only set the status on the first call (the dispatch will trigger
    // another call to this Servlet)
    if (resp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        AsyncContext ac = req.startAsync();
        ac.dispatch();
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:12,代码来源:TestErrorReportValve.java

示例2: service

import javax.servlet.AsyncContext; //导入依赖的package包/类
public void service(HttpServletRequest request, HttpServletResponse response) {
  if (transport == null) {
    transport = CseContext.getInstance().getTransportManager().findTransport(Const.RESTFUL);
  }

  // 异步场景
  final AsyncContext asyncCtx = request.startAsync();
  asyncCtx.addListener(restAsyncListener);
  asyncCtx.setTimeout(ServletConfig.getServerTimeout());

  HttpServletRequestEx requestEx = new StandardHttpServletRequestEx(request);
  HttpServletResponseEx responseEx = new StandardHttpServletResponseEx(response);

  RestServletProducerInvocation restProducerInvocation = new RestServletProducerInvocation();
  restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:17,代码来源:ServletRestDispatcher.java

示例3: doGet

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    track("doGet-");
    AsyncContext ctx = req.startAsync();
    ctx.setTimeout(3000);
    ctx.addListener(new TrackingListener(true, false, "/async"));

    String loopsParam = req.getParameter("loops");
    Integer loopsAttr = (Integer) req.getAttribute("loops");

    int loops = 0;
    if (loopsAttr != null) {
        loops = loopsAttr.intValue();
    } else if (loopsParam != null) {
        loops = Integer.parseInt(loopsParam);
    }

    if (loops > 1) {
        loops--;
        req.setAttribute("loops", Integer.valueOf(loops));
        ctx.dispatch();
    } else
        throw new ServletException();
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:27,代码来源:TestAsyncContextImpl.java

示例4: processRequest

import javax.servlet.AsyncContext; //导入依赖的package包/类
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	try (PrintWriter output = response.getWriter()) {
		output.println("<html>");
		output.println("<head>");
		output.println("<title>Reading asynchronously</title>");
		output.println("</head>");
		output.println("<body>");
		output.println("<h1>Reading asynchronously</h1>");

		AsyncContext context = request.startAsync();
		ServletInputStream input = request.getInputStream();
		input.setReadListener(new ReadingListener(input, context));

		output.println("</body>");
		output.println("</html>");
	}
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:20,代码来源:ReadingServlet.java

示例5: onProxyResponseFailure

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void onProxyResponseFailure(final HttpServletRequest clientRequest, final HttpServletResponse proxyResponse,
		final Response serverResponse, final Throwable failure) {
	_log.warn(failure.toString());

	if (proxyResponse.isCommitted()) {
		// Parent behavior
		super.onProxyResponseFailure(clientRequest, proxyResponse, serverResponse, failure);
	} else {
		proxyResponse.resetBuffer();
		if (failure instanceof TimeoutException) {
			proxyResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
		} else {

			// Unavailable business server as JSON response
			proxyResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			proxyResponse.setContentType("application/json");
			try {
				proxyResponse.getOutputStream().write("{\"code\":\"business-down\"}".getBytes(StandardCharsets.UTF_8));
			} catch (final IOException ioe) {
				_log.warn("Broken proxy stream", ioe);
			}
		}
		proxyResponse.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString());
		final AsyncContext asyncContext = clientRequest.getAsyncContext();
		asyncContext.complete();
	}
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:29,代码来源:BackendProxyServlet.java

示例6: main

import javax.servlet.AsyncContext; //导入依赖的package包/类
public static void main(String[] args) {

        Javalin app = Javalin.create().port(5454).start();

        app.get("/test-custom", ctx -> {
            AsyncContext asyncContext = ctx.request().startAsync();
            simulateAsyncTask(() -> {
                ctx.status(418);
                asyncContext.complete();
            });
        });

        app.get("/test-async", ctx -> ctx.async(() -> {
            CompletableFuture<Void> future = new CompletableFuture<>();
            simulateAsyncTask(() -> {
                ctx.status(418);
                future.complete(null);
            });
            return future;
        }));

    }
 
开发者ID:tipsy,项目名称:javalin,代码行数:23,代码来源:AsyncExample.java

示例7: doGet

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void doGet(HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {
    final AsyncContext ctx = req.startAsync();
    ctx.start(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(THREAD_SLEEP_TIME);
                resp.setHeader("A", "xyz");
                resp.setContentType("text/plain");
                resp.setContentLength("OK".getBytes().length);
                resp.getWriter().print("OK");
                ctx.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:22,代码来源:TestAsyncContextImpl.java

示例8: doPut

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void doPut(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final AsyncContext ac = req.startAsync();
    ac.start(new Runnable() {
        @Override
        public void run() {
            resp.setContentType("text/plain");
            resp.setCharacterEncoding("UTF-8");
            try {
                resp.getWriter().print("OK");
            } catch (IOException e) {
                // Should never happen. Test will fail if it does.
            }
            ac.complete();
        }
    });
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:19,代码来源:TestAbstractHttp11Processor.java

示例9: init

import javax.servlet.AsyncContext; //导入依赖的package包/类
/**
 * Method for stream initialization
 * @param clientUri - Client Uri
 * @param request - The servlet request object
 * @param response - The servlet Response Object
 */
private void init(String clientUri,HttpServletRequest request, HttpServletResponse response){
	LOG.info("Response Stream Inititated");
	try{
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(72*60*60);
		EventClient client = new EventClient();
		client.connectToClient(clientUri);
		response.setHeader("Content-Type", "text/event-stream");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Connection", "keep-alive");
		AsyncContext asyncContext = request.startAsync(request,response);
		asyncContext.setTimeout(72*60*60*1000);
		asyncContext.getResponse().setBufferSize(1200);
		try {
			asyncContext.getResponse().flushBuffer();
		} catch (IOException e1) {
			ErrorLog.logError(e1.getMessage(),e1.getStackTrace());
		}
		ServletContext servletContext = request.getServletContext();
		Map<String,AsyncContext> responseStreams = (ConcurrentHashMap<String,AsyncContext>) servletContext.getAttribute("responseStreams");
		responseStreams.put(clientUri,asyncContext);
	} catch (Exception e){
		ErrorLog.logError(e.getMessage(),e.getStackTrace());
	}
}
 
开发者ID:opendaylight,项目名称:fpc,代码行数:32,代码来源:EventServer.java

示例10: doDispatch

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    final AsyncContext ac = request.startAsync(request, response);

    ac.setTimeout(TIME_OUT);

    // FIXME: convert to Lambda
    FutureTask task = new FutureTask(new Runnable() {

        @Override
        public void run() {
            try {
                logger.debug("Dispatching request " + request);
                AsyncDispatcherServlet.super.doDispatch(request, response);
                logger.debug("doDispatch returned from processing request " + request);
                ac.complete();
            } catch (Exception ex) {
                logger.error("Error in async request", ex);
            }
        }
    }, null);

    ac.addListener(new AsyncDispatcherServletListener(task));
    exececutor.execute(task);
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:27,代码来源:AsyncDispatcherServlet.java

示例11: testAsyncServletRequestHasListenerAdded

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Test
public void testAsyncServletRequestHasListenerAdded() throws IOException, ServletException {
    AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");

    AsyncContext asyncContext = Mockito.mock(AsyncContext.class);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
    Mockito.when(request.getMethod()).thenReturn("TEST_METHOD");
    Mockito.when(request.isAsyncStarted()).thenReturn(true);
    Mockito.when(request.getAsyncContext()).thenReturn(asyncContext);

    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    FilterChain chain = Mockito.mock(FilterChain.class);

    servletFilter.doFilter(request, response, chain);

    Mockito.verify(asyncContext, Mockito.times(1)).addListener(Mockito.any());
}
 
开发者ID:aws,项目名称:aws-xray-sdk-java,代码行数:21,代码来源:AWSXRayServletFilterTest.java

示例12: writeStock

import javax.servlet.AsyncContext; //导入依赖的package包/类
public void writeStock(AsyncContext actx, Stock stock) {
    HttpServletResponse response = (HttpServletResponse)actx.getResponse();
    try {
        PrintWriter writer = response.getWriter();
        writer.write("STOCK#");//make client parsing easier
        writer.write(stock.getSymbol());
        writer.write("#");
        writer.write(stock.getValueAsString());
        writer.write("#");
        writer.write(stock.getLastChangeAsString());
        writer.write("#");
        writer.write(String.valueOf(stock.getCnt()));
        writer.write("\n");
        writer.flush();
        response.flushBuffer();
    }catch (IOException x) {
        try {actx.complete();}catch (Exception ignore){/* Ignore */}
    }
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:20,代码来源:AsyncStockServlet.java

示例13: service

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Override
public void service(ServletRequest req, ServletResponse resp)
        throws ServletException, IOException {
    if (DispatcherType.ASYNC != req.getDispatcherType()) {
        AsyncContext asyncContext;
        if ("y".equals(req.getParameter(CUSTOM_REQ_RESP))) {
            asyncContext = req.startAsync(
                    new ServletRequestWrapper(req),
                    new ServletResponseWrapper(resp));
        } else {
            asyncContext = req.startAsync();
        }
        if ("y".equals(req.getParameter(EMPTY_DISPATCH))) {
            asyncContext.dispatch();
        } else {
            asyncContext.dispatch("/target");
        }
        try {
            asyncContext.dispatch("/nonExistingServlet");
            TestAsyncContextImpl.track("FAIL");
        } catch (IllegalStateException e) {
            TestAsyncContextImpl.track("OK");
        }
    } else {
        TestAsyncContextImpl.track("DispatchingGenericServletGet-");
    }
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:28,代码来源:TestAsyncContextImpl.java

示例14: testGetAsyncContext

import javax.servlet.AsyncContext; //导入依赖的package包/类
@Test
public void testGetAsyncContext() {
  AsyncContext asyncContext =
      Deencapsulation.getField(VertxServerRequestToHttpServletRequest.class, "EMPTY_ASYNC_CONTEXT");

  Assert.assertSame(asyncContext, request.getAsyncContext());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:8,代码来源:TestVertxServerRequestToHttpServletRequest.java

示例15: compelete

import javax.servlet.AsyncContext; //导入依赖的package包/类
public static void compelete(AsyncContext asyncContext) {
    try {
        asyncContext.complete();
    } catch (Exception e) {
        LOGGER.error("unexpect error", e);
    }
}
 
开发者ID:wxz1211,项目名称:dooo,代码行数:8,代码来源:AsyncContextUtils.java


注:本文中的javax.servlet.AsyncContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。