當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。