Handle initial HTTP portion of the handshake.

@param channelContext
@param request
@throws Exception
962679
protected void handleHttpRequest(final ChannelHandlerContext channelContext, final HttpRequest request) throws Exception {
        if (isWebSocketsUpgradeRequest( request )) {

            final Handshake handshake = findHandshake( request );

            if (handshake != null) {

                HttpResponse response = handshake.generateResponse( request );

                response.addHeader( Names.UPGRADE, Values.WEBSOCKET );
                response.addHeader( Names.CONNECTION, Values.UPGRADE );

                final ChannelPipeline pipeline = channelContext.getChannel().getPipeline();
                reconfigureUpstream( pipeline, handshake );

                Channel channel = channelContext.getChannel();
                ChannelFuture future = channel.write( response );
                future.addListener( new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) throws Exception {
                        reconfigureDownstream( pipeline, handshake );
                        pipeline.replace( ServerHandshakeHandler.this, "websocket-disconnection-negotiator", new WebSocketDisconnectionNegotiator() );
                        forwardConnectEventUpstream( channelContext );
                        decodeHost( channelContext, request );
                        decodeSession( channelContext, request );
                    }
                } );

                return;
            }
        }

        // Send an error page otherwise.
        sendHttpResponse( channelContext, request, new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN ) );
    }
701302
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
        FullHttpRequest request =  newHandshakeRequest();

        HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
        if (decoder == null) {
            HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
            if (codec == null) {
               promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                       "a HttpResponseDecoder or HttpClientCodec"));
               return promise;
            }
        }

        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ChannelPipeline p = future.channel().pipeline();
                    ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                    if (ctx == null) {
                        ctx = p.context(HttpClientCodec.class);
                    }
                    if (ctx == null) {
                        promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                                "a HttpRequestEncoder or HttpClientCodec"));
                        return;
                    }
                    p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                    promise.setSuccess();
                } else {
                    promise.setFailure(future.cause());
                }
            }
        });
        return promise;
    }
590912
private void checkHandler(SipServletRequest request) {
		MobicentsSipSession sipSessionImpl = (MobicentsSipSession)request.getSession();
		if(sipSessionImpl.getHandler() == null) {
			try {
				sipSessionImpl.setHandler(sipContext.getServletHandler());
//				((SipApplicationSessionImpl)sipSessionImpl.getApplicationSession()).setSipContext(sipContext);
			} catch (ServletException se) {
				//should never happen
				logger.error("Impossible to set the default handler on the newly created request "+ request.toString(),se);
			} 
		}
	}
19109
public void setRequest(Object request)
    {
        ExternalContext ctx = _MyFacesExternalContextHelper.firstInstance.get();
        
        if (ctx == null)
        {
            throw new UnsupportedOperationException();
        }
        
        ctx.setRequest(request);
    }
864481
@SuppressWarnings("WeakerAccess")
    protected void onExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.debug("Exception caught: {}", cause.getMessage(), cause);
    }
1167733
public void handle(Request request, Response response) throws Exception {
		if (Environment.isDevelopment()) {
			this.middlewares = this.middlewareFactory.create();
		}
		
		try {
			handle(request, response, new ArrayList<Middleware>(Arrays.asList(middlewares)));
		} catch (Exception e) {
			if (exceptionHandler != null) {
				exceptionHandler.handle(e, request, response);
			} else {
				throw e;
			}
		}
	}
1362851
public void init() throws ChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "UDP Channel: " + getConfig().getExternalName() + " listening port: " + String.valueOf(getConfig().getPort()));
        }
    }
928472
@Override
	public void handleRequest(final Request request) {
		if (!isInitialised()) {
			getOrCreateComponentModel().delegate = new SafetyContainerDelegate(UIContextHolder.
					getCurrent());
			setInitialised(true);
		}

		try {
			UIContext delegate = getComponentModel().delegate;
			UIContextHolder.pushContext(delegate);

			try {
				for (int i = 0; i < shim.getChildCount(); i++) {
					shim.getChildAt(i).serviceRequest(request);
				}

				delegate.doInvokeLaters();
			} finally {
				UIContextHolder.popContext();
			}
		} catch (final ActionEscape e) {
			// We don't want to catch ActionEscapes (e.g. ForwardExceptions)
			throw e;
		} catch (final Exception e) {
			if (isAjaxOrTargetedRequest(request)) {
				throw new SystemException(e.getMessage(), e);
			} else {
				setAttribute(ERROR_KEY, e);
			}
		}
	}
1007085
@Override
    public final void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

        AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
        if (authState.getAuthScheme() == null) {

            HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            AuthCache authCache = new BasicAuthCache();
            authCache.put(targetHost, new BasicScheme());
            context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        }
    }
361276
public void start(String channelId) throws AlluxioStatusException {
    try {
      LOG.debug("Starting SASL handshake for ChannelId:{}", channelId);
      // Send the server initial message.
      mRequestObserver.onNext(mSaslHandshakeClientHandler.getInitialMessage(channelId));
      // Wait until authentication status changes.
      mAuthenticated.get(mGrpcAuthTimeoutMs, TimeUnit.MILLISECONDS);
    } catch (SaslException se) {
      throw new UnauthenticatedException(se.getMessage(), se);
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
      throw new UnavailableException(ie.getMessage(), ie);
    } catch (ExecutionException e) {
      Throwable cause = (e.getCause() != null) ? e.getCause() : e;
      if (cause != null && cause instanceof StatusRuntimeException) {
        StatusRuntimeException sre = (StatusRuntimeException) cause;
        // If caught unimplemented, that means server does not support authentication.
        if (sre.getStatus().getCode() == Status.Code.UNIMPLEMENTED) {
          throw new UnauthenticatedException("Authentication is disabled on target host.");
        }
        throw AlluxioStatusException.fromStatusRuntimeException((StatusRuntimeException) cause);
      }
      throw new UnknownException(cause.getMessage(), cause);
    } catch (TimeoutException e) {
      throw new UnavailableException(e);
    }
  }
604562
@Override
    public void update(ChannelData inputData) {
        this.handshakeErrorTracker = createSSLHandshakeErrorTracker(inputData);
        this.sslConfig.updateChannelData(inputData);
    }
825576
@Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
      throws Exception {
    if (msg instanceof SendGrpcFrameCommand) {
      sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise);
    } else if (msg instanceof SendResponseHeadersCommand) {
      sendResponseHeaders(ctx, (SendResponseHeadersCommand) msg, promise);
    } else if (msg instanceof CancelServerStreamCommand) {
      cancelStream(ctx, (CancelServerStreamCommand) msg, promise);
    } else if (msg instanceof ForcefulCloseCommand) {
      forcefulClose(ctx, (ForcefulCloseCommand) msg, promise);
    } else {
      AssertionError e =
          new AssertionError("Write called for unexpected type: " + msg.getClass().getName());
      ReferenceCountUtil.release(msg);
      promise.setFailure(e);
      throw e;
    }
  }
754879
private void handleAuthResponse(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    if (saslClient.isComplete()) {
      checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
      return;
    }

    ByteBuf challengeBuf = SaslAuthResponse.challenge(msg);
    byte[] challenge = new byte[challengeBuf.readableBytes()];
    challengeBuf.readBytes(challenge);
    byte[] evaluatedBytes = saslClient.evaluateChallenge(challenge);

    if (evaluatedBytes != null) {
      ByteBuf content;

      // This is needed against older server versions where the protocol does not
      // align on cram and plain, the else block is used for all the newer cram-sha*
      // mechanisms.
      //
      // Note that most likely this is only executed in the CRAM-MD5 case only, but
      // just to play it safe keep it for both mechanisms.
      if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
        String[] evaluated = new String(evaluatedBytes).split(" ");
        content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
      } else {
        content = Unpooled.wrappedBuffer(evaluatedBytes);
      }

      ByteBuf request = ctx.alloc().buffer();
      SaslStepRequest.init(request);
      SaslStepRequest.mechanism(selectedMechanism, request);
      SaslStepRequest.challengeResponse(content, request);

      ChannelFuture future = ctx.writeAndFlush(request);
      future.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
          if (!future.isSuccess()) {
            LOGGER.warn("Error during SASL Auth negotiation phase.", future);
            originalPromise().setFailure(future.cause());
          }
        }
      });
    } else {
      throw new AuthenticationException("SASL Challenge evaluation returned null.");
    }

  }
1035342
private void sendHandshake(ChannelHandlerContext ctx) {
    boolean needToFlush = false;

    // Iterate until there is nothing left to write.
    while (true) {
      buffer = getOrCreateBuffer(ctx.alloc());
      try {
        handshaker.getBytesToSendToPeer(buffer);
      } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
      }
      if (!buffer.isReadable()) {
        break;
      }

      needToFlush = true;
      @SuppressWarnings("unused") // go/futurereturn-lsc
      Future<?> possiblyIgnoredError = ctx.write(buffer);
      buffer = null;
    }

    // If something was written, flush.
    if (needToFlush) {
      ctx.flush();
    }
  }
1036044
void handleRequest(ByteBuf buffer) {
    long requestId = buffer.readLong();

    try {
      Object request = readRequest(buffer);
      HandlerHolder handler = handlers.get(request.getClass());
      if (handler != null) {
        handler.context.executor().execute(() -> handleRequest(requestId, request, handler));
      } else {
        handleRequestFailure(requestId, new SerializationException("unknown message type: " + request.getClass()), this.context);
      }
    } catch (SerializationException e) {
      handleRequestFailure(requestId, e, this.context);
    } finally {
      buffer.release();
    }
  }
670254
@Override
	public void handleRequest(final Request request) {
		super.handleRequest(request);

		WComponent visibleDialog = getVisible();

		if (visibleDialog != null) {
			visibleDialog.serviceRequest(request);
		}
	}
554080
public void handleRequest(String request) {
        if (messageListener != null) {
            log.debug("Received Http request");
            messageListener.onInboundMessage(new RawMessage(request), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received Http request:" + NEWLINE + request);
            }
        }
    }