Package org.eclipse.jetty.continuation

Examples of org.eclipse.jetty.continuation.Continuation


    this.continuationTimeoutMillis = continuationTimeoutMillis;
    log.info(toString());
  }

  private void executeContinuation(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) {
    final Continuation continuation = ContinuationSupport.getContinuation(baseRequest);
    continuation.suspend();
    if (continuationTimeoutMillis > 0) {
      continuation.setTimeout(continuationTimeoutMillis);
    }
    executor.execute(new Runnable() {

      @Override
      public void run() {
        try {
          process(target, baseRequest, request, response);
        } catch (final Exception e) {
          log.error("Request failed", e);
        } finally {
          continuation.complete();
        }

      }
    });
View Full Code Here


    public void process(Request request, HttpServletResponse response) {
        Client client = null;
        boolean adminMode = false;

        Continuation continuation = ContinuationSupport.getContinuation(request);
        continuation.suspend(response);
        String jsonp = null;
        try {
            // first check for a catalog update and purge the cached connections
            // if one has happened since we were here last
            if (m_shouldUpdateCatalog.compareAndSet(true, false))
            {
                m_connections.closeAll();
                // Just null the old object so we'll create a new one with
                // updated state below
                m_connections = null;
            }

            if (m_connections == null) {
                int port = VoltDB.instance().getConfig().m_port;
                int adminPort = VoltDB.instance().getConfig().m_adminPort;
                String externalInterface = VoltDB.instance().getConfig().m_externalInterface;
                String adminInterface = "localhost";
                String clientInterface = "localhost";
                if (externalInterface != null && !externalInterface.isEmpty()) {
                    clientInterface = externalInterface;
                    adminInterface = externalInterface;
                }
                //If individual override is available use them.
                if (VoltDB.instance().getConfig().m_clientInterface.length() > 0) {
                    clientInterface = VoltDB.instance().getConfig().m_clientInterface;
                }
                if (VoltDB.instance().getConfig().m_adminInterface.length() > 0) {
                    adminInterface = VoltDB.instance().getConfig().m_adminInterface;
                }
                m_connections = new AuthenticatedConnectionCache(10, clientInterface, port, adminInterface, adminPort);
            }

            jsonp = request.getParameter("jsonp");
            if (request.getMethod().equalsIgnoreCase("POST")) {
                int queryParamSize = request.getContentLength();
                if (queryParamSize > 150000) {
                    // We don't want to be building huge strings
                    throw new Exception("Query string too large: " + String.valueOf(request.getContentLength()));
                }
                if (queryParamSize == 0) {
                    throw new Exception("Received POST with no parameters in the body.");
                }
            }

            String username = request.getParameter("User");
            String password = request.getParameter("Password");
            String hashedPassword = request.getParameter("Hashedpassword");
            String procName = request.getParameter("Procedure");
            String params = request.getParameter("Parameters");
            String admin = request.getParameter("admin");

            // check for admin mode
            if (admin != null) {
                if (admin.compareToIgnoreCase("true") == 0) {
                    adminMode = true;
                }
            }

            // null procs are bad news
            if (procName == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                continuation.complete();
                return;
            }

            // The SHA-1 hash of the password
            byte[] hashedPasswordBytes = null;

            if (password != null) {
                try {
                    // Create a MessageDigest every time because MessageDigest is not thread safe (ENG-5438)
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException("JVM doesn't support SHA-1 hashing. Please use a supported JVM", e);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("JVM doesn't support UTF-8. Please use a supported JVM", e);
                }
            }
            // note that HTTP Var "Hashedpassword" has a higher priority
            // Hashedassword must be a 40-byte hex-encoded SHA-1 hash (20 bytes unencoded)
            if (hashedPassword != null) {
                if (hashedPassword.length() != 40) {
                    throw new Exception("Hashedpassword must be a 40-byte hex-encoded SHA-1 hash (20 bytes unencoded).");
                }
                try {
                    hashedPasswordBytes = Encoder.hexDecode(hashedPassword);
                }
                catch (Exception e) {
                    throw new Exception("Hashedpassword must be a 40-byte hex-encoded SHA-1 hash (20 bytes unencoded).");
                }
            }

            assert((hashedPasswordBytes == null) || (hashedPasswordBytes.length == 20));

            // get a connection to localhost from the pool
            client = m_connections.getClient(username, password, hashedPasswordBytes, adminMode);

            JSONProcCallback cb = new JSONProcCallback(request, continuation, jsonp);
            boolean success;
            if (params != null) {
                ParameterSet paramSet = null;
                try {
                    paramSet = ParameterSet.fromJSONString(params);
                }
                // if decoding params has a fail, then fail
                catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    continuation.complete();
                    return;
                }
                // if the paramset has content, but decodes to null, fail
                if (paramSet == null) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    continuation.complete();
                    return;
                }
                success = client.callProcedure(cb, procName, paramSet.toArray());
            }
            else {
                success = client.callProcedure(cb, procName);
            }
            if (!success) {
                throw new Exception("Server is not accepting work at this time.");
            }
            if (adminMode) {
                cb.waitForResponse();
            }
        }
        catch (java.net.ConnectException c_ex)
        {
            // Clients may attempt to connect to VoltDB before the server
            // is completely initialized (our tests do this, for example).
            // Don't print a stack trace, and return a server unavailable reason.
            ClientResponseImpl rimpl = new ClientResponseImpl(ClientResponse.SERVER_UNAVAILABLE, new VoltTable[0], c_ex.getMessage());
            String msg = rimpl.toJSONString();
            if (jsonp != null) {
                msg = String.format("%s( %s )", jsonp, msg);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            request.setHandled(true);
            try {
                response.getWriter().print(msg);
                continuation.complete();
            } catch (IOException e1) {}
        }
        catch (Exception e) {
            String msg = e.getMessage();
            m_rate_limited_log.log("JSON interface exception: " + msg, EstTime.currentTimeMillis());
            ClientResponseImpl rimpl = new ClientResponseImpl(ClientResponse.UNEXPECTED_FAILURE, new VoltTable[0], msg);
            msg = rimpl.toJSONString();
            if (jsonp != null) {
                msg = String.format("%s( %s )", jsonp, msg);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            request.setHandled(true);
            try {
                response.getWriter().print(msg);
                continuation.complete();
            } catch (IOException e1) {}
        }
        finally {
            if (client != null) {
                assert(m_connections != null);
View Full Code Here

    public AbstractHandler configureHandler() throws Exception {
        return new AbstractHandler() {
            public void handle(String s, Request request, HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
                resp.setContentType("text/plain;charset=utf-8");
                resp.setStatus(200);
                final Continuation continuation = ContinuationSupport.getContinuation(req);
                continuation.suspend();
                final PrintWriter writer = resp.getWriter();
                executorService.submit(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            logger.error("Failed to sleep for 100 ms.", e);
                        }
                        logger.info("Delivering part1.");
                        writer.write("part1");
                        writer.flush();
                    }
                });
                executorService.submit(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            logger.error("Failed to sleep for 200 ms.", e);
                        }
                        logger.info("Delivering part2.");
                        writer.write("part2");
                        writer.flush();
                        continuation.complete();
                    }
                });
                request.setHandled(true);
            }
        };
View Full Code Here

    }

    private class SlowHandler extends AbstractHandler {
        public void handle(String target, Request baseRequest, HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
            final Continuation continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1500);
                        response.getOutputStream().print(MSG);
                        response.getOutputStream().flush();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }).start();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(3000);
                        response.getOutputStream().print(MSG);
                        response.getOutputStream().flush();
                        continuation.complete();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
View Full Code Here

    private class ExpectExceptionHandler extends AbstractHandler {
        public void handle(String target, Request baseRequest, HttpServletRequest request, final HttpServletResponse response)
                throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            final Continuation continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        response.getOutputStream().print(MSG);
                        response.getOutputStream().flush();
View Full Code Here

    private class SlowHandler extends AbstractHandler {
        public void handle(String target, Request baseRequest, HttpServletRequest request, final HttpServletResponse response)
                throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
            final Continuation continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(SLEEPTIME_MS);
                        response.getOutputStream().print(MSG);
                        response.getOutputStream().flush();
                        continuation.complete();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
View Full Code Here

            if (consumer == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            final Continuation continuation = ContinuationSupport.getContinuation(request);

            // are we suspended and a request is dispatched initially?
            if (consumer.isSuspended() && continuation.isInitial()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            if (continuation.isInitial()) {
                // a new request so create an exchange
                final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);
                if (consumer.getEndpoint().isBridgeEndpoint()) {
                    exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
                }
                if (consumer.getEndpoint().isDisableStreamCache()) {
                    exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
                }
                exchange.setIn(new HttpMessage(exchange, request, response));

                if (log.isTraceEnabled()) {
                    log.trace("Suspending continuation of exchangeId: " + exchange.getExchangeId());
                }
                continuation.suspend();

                // use the asynchronous API to process the exchange
                consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {
                    public void done(boolean doneSync) {
                        if (log.isTraceEnabled()) {
                            log.trace("Resuming continuation of exchangeId: " + exchange.getExchangeId());
                        }
                        // resume processing after both, sync and async callbacks
                        continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange);
                        continuation.resume();
                    }
                });
                return;
            }

            if (continuation.isResumed()) {
                // a re-dispatched request containing the processing result
                Exchange exchange = (Exchange) continuation.getAttribute(EXCHANGE_ATTRIBUTE_NAME);
                if (log.isTraceEnabled()) {
                    log.trace("Resuming continuation of exchangeId: " + exchange.getExchangeId());
                }

                // now lets output to the response
View Full Code Here

        }
       
        final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME);
        if (result == null) {
            // no asynchronous result so leverage continuation
            final Continuation continuation = ContinuationSupport.getContinuation(request);
            if (continuation.isInitial() && continuationTimeout != null) {
                // set timeout on initial
                continuation.setTimeout(continuationTimeout);
            }

            // are we suspended and a request is dispatched initially?
            if (consumer.isSuspended() && continuation.isInitial()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            if (continuation.isExpired()) {
                String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID);
                // remember this id as expired
                expiredExchanges.put(id, id);
                log.warn("Continuation expired of exchangeId: {}", id);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            // a new request so create an exchange
            final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);

            if (consumer.getEndpoint().isBridgeEndpoint()) {
                exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
            }
            if (consumer.getEndpoint().isDisableStreamCache()) {
                exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
            }
           
            HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
           
            exchange.setIn(new HttpMessage(exchange, request, response));
            // set context path as header
            String contextPath = consumer.getEndpoint().getPath();
            exchange.getIn().setHeader("CamelServletContextPath", contextPath);
           
            String httpPath = (String)exchange.getIn().getHeader(Exchange.HTTP_PATH);
            // here we just remove the CamelServletContextPath part from the HTTP_PATH
            if (contextPath != null
                && httpPath.startsWith(contextPath)) {
                exchange.getIn().setHeader(Exchange.HTTP_PATH,
                        httpPath.substring(contextPath.length()));
            }

            if (log.isTraceEnabled()) {
                log.trace("Suspending continuation of exchangeId: {}", exchange.getExchangeId());
            }
            continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId());

            // we want to handle the UoW
            try {
                consumer.createUoW(exchange);
            } catch (Exception e) {
                log.error("Error processing request", e);
                throw new ServletException(e);
            }

            // must suspend before we process the exchange
            continuation.suspend();

            ClassLoader oldTccl = overrideTccl(exchange);

            if (log.isTraceEnabled()) {
                log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
            }
            // use the asynchronous API to process the exchange
           
            consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {
                public void done(boolean doneSync) {
                    // check if the exchange id is already expired
                    boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null;
                    if (!expired) {
                        if (log.isTraceEnabled()) {
                            log.trace("Resuming continuation of exchangeId: {}", exchange.getExchangeId());
                        }
                        // resume processing after both, sync and async callbacks
                        continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange);
                        continuation.resume();
                    } else {
                        log.warn("Cannot resume expired continuation of exchangeId: {}", exchange.getExchangeId());
                    }
                }
            });
View Full Code Here

    }
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Continuation continuation = ContinuationSupport.getContinuation(request);
    if (continuation.isExpired()) {
      // timeout - just send a blank response and tell the connection that its continuation has timed out
      String clientId = (String) continuation.getAttribute(CLIENT_ID);
      if (clientId != null) {
        // TODO will this always get the correct continuation?
        _connectionManager.longPollHttpTimeout(clientId, continuation);
      }
      return;
View Full Code Here

            handleConnect(request, response);
            return;
        }

        final InputStream in = request.getInputStream();
        final Continuation continuation = ContinuationSupport.getContinuation(request);

        if (!continuation.isInitial()) {
            response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT); // Need better test that isInitial
            return;
        }

        String uri = request.getRequestURI();
        if (request.getQueryString() != null) {
            uri += "?" + request.getQueryString();
        }

        final HttpURI url = proxyHttpURI(request, uri);

        logger.debug("proxy {}-->{}", uri, url);

        if (url == null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        final HttpExchange exchange = new CustomHttpExchange(continuation, response, request);

        exchange.setScheme(HttpSchemes.HTTPS.equals(request.getScheme()) ? HttpSchemes.HTTPS_BUFFER : HttpSchemes.HTTP_BUFFER);
        exchange.setMethod(request.getMethod());
        exchange.setURL(url.toString());
        exchange.setVersion(request.getProtocol());

        logger.debug("{} {} {}", request.getMethod(), url, request.getProtocol());

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase(Locale.ENGLISH);
            if (!connectionHdr.contains("keep-alive") && !connectionHdr.contains("close")) {
                connectionHdr = null;
            }
        }

        // force host
        if (_hostHeader != null) {
            exchange.setRequestHeader("Host", _hostHeader);
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        long contentLength = -1;
        Enumeration<?> enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase(Locale.ENGLISH);

            if ("transfer-encoding".equals(lhdr)) {
                if (request.getHeader("transfer-encoding").contains("chunk")) {
                    hasContent = true;
                }
            }

            if (_DontProxyHeaders.contains(lhdr)) {
                continue;
            }
            if (connectionHdr != null && connectionHdr.contains(lhdr)) {
                continue;
            }
            if (_hostHeader != null && "host".equals(lhdr)) {
                continue;
            }

            if ("content-type".equals(lhdr)) {
                hasContent = true;
            } else if ("content-length".equals(lhdr)) {
                contentLength = request.getContentLength();
                exchange.setRequestHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(contentLength));
                if (contentLength > 0) {
                    hasContent = true;
                }
            } else if ("x-forwarded-for".equals(lhdr)) {
                xForwardedFor = true;
            }

            Enumeration<?> vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    logger.debug("{}: {}", hdr, val);

                    exchange.setRequestHeader(hdr, val);
                }
            }
        }

        // Proxy headers
        exchange.setRequestHeader("Via", "1.1 (jetty)");
        if (!xForwardedFor) {
            exchange.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());
            exchange.addRequestHeader("X-Forwarded-Proto", request.getScheme());
            exchange.addRequestHeader("X-Forwarded-Host", request.getHeader("Host"));
            exchange.addRequestHeader("X-Forwarded-Server", request.getLocalName());
        }

        if (hasContent) {
            exchange.setRequestContentSource(in);
        }

        customizeExchange(exchange, request);

        /*
         * we need to set the timeout on the continuation to take into
         * account the timeout of the HttpClient and the HttpExchange
         */
        long ctimeout = (_client.getTimeout() > exchange.getTimeout()) ? _client.getTimeout() : exchange.getTimeout();

        // continuation fudge factor of 1000, underlying components
        // should fail/expire first from exchange
        if (ctimeout == 0) {
            continuation.setTimeout(0)// ideally never times out
        } else {
            continuation.setTimeout(ctimeout + 1000);
        }

        customizeContinuation(continuation);

        continuation.suspend(response);
        _client.send(exchange);
    }
View Full Code Here

TOP

Related Classes of org.eclipse.jetty.continuation.Continuation

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.