Handles the cleartext HTTP upgrade event.
<p>
If an upgrade occurred, message needs to be dispatched to
the correct service/resource and response should be delivered over stream 1
(the stream specifically reserved for cleartext HTTP upgrade).
777256
@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
            FullHttpRequest upgradedRequest = ((HttpServerUpgradeHandler.UpgradeEvent) evt).upgradeRequest();

            // Construct new HTTP Request
            HttpRequest httpRequest = new DefaultHttpRequest(
                    new HttpVersion(Constants.HTTP_VERSION_2_0, true), upgradedRequest.method(),
                    upgradedRequest.uri(), upgradedRequest.headers());

            HttpCarbonRequest requestCarbonMessage = setupCarbonRequest(httpRequest, this);
            requestCarbonMessage.addHttpContent(new DefaultLastHttpContent(upgradedRequest.content()));
            notifyRequestListener(this, requestCarbonMessage, 1);
        }
    }
1166781
protected boolean isSwitchingToNonHttp1Protocol(HttpResponse msg) {
        if (msg.status().code() != HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
            return false;
        }
        String newProtocol = msg.headers().get(HttpHeaderNames.UPGRADE);
        return newProtocol == null ||
                !newProtocol.contains(HttpVersion.HTTP_1_0.text()) &&
                !newProtocol.contains(HttpVersion.HTTP_1_1.text());
    }
549574
def handle_get_request(self, environ, start_response):
        """"""
        connections = [
            s.strip()
            for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        transport = environ.get('HTTP_UPGRADE', '').lower()
        if 'upgrade' in connections and transport in self.upgrade_protocols:
            self.server.logger.info('%s: Received request to upgrade to %s',
                                    self.sid, transport)
            return getattr(self, '_upgrade_' + transport)(environ,
                                                          start_response)
        try:
            packets = self.poll()
        except exceptions.QueueEmpty:
            exc = sys.exc_info()
            self.close(wait=False)
            six.reraise(*exc)
        return packets
1258218
private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
            throws Exception {
        if (headers.isEndStream()) {
            ByteBuf content = ctx.alloc().buffer();
            content.writeBytes(RESPONSE_BYTES.duplicate());
            ByteBufUtil.writeAscii(content, " - via HTTP/2");
            sendResponse(ctx, content);
        }
    }
261961
public void postUpdate()
    {
        if (current != null)
        {
            final Class<? extends State> next = current.checkTransitions(last);
            if (next != null)
            {
                changeState(next);
            }
        }
    }
1214125
def _handle_clear(self, load):
        '''
        
        '''
        log.trace('Clear payload received with command %s', load['cmd'])
        cmd = load['cmd']
        if cmd.startswith('__'):
            return False
        if self.opts['master_stats']:
            start = time.time()
        ret = getattr(self.clear_funcs, cmd)(load), {'fun': 'send_clear'}
        if self.opts['master_stats']:
            stats = salt.utils.event.update_stats(self.stats, start, load)
            self._post_stats(stats)
        return ret
543324
private void sendNotModified(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
        setDateHeader(response);

        this.sendAndCleanupConnection(ctx, response);
    }
245198
public void handleNotFlushedMessage(ControlNotFlushed cMsg)

  throws SIIncorrectCallException, SIErrorException, SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(this, tc, "handleNotFlushedMessage", new Object[] { cMsg });

    SIBUuid12 streamID = cMsg.getGuaranteedStreamUUID();
    //Synchronize to resolve racing messages.
    synchronized (flushMap)
    {
      FlushQueryRecord entry = flushMap.get(streamID);
      // make sure the request ID matches.
      long reqId = cMsg.getRequestID();
      //if there is no entry or the entry's request ID does not match then
      //it must have been a stale request and we ignore it.
      if ((entry != null) && (entry.requestID == reqId))
      {
        // ASSERT.isTrue(entry.cache != null)

        // The assertion basically means that we should only receive
        // NOTFLUSHED if the original query was AREYOUFLUSHED.  The
        // only legal reply to REQUESTFLUSH is, eventually, FLUSHED.

        // Our original query was for "are you flushed" and we now
        // have the reply, so:
        // 1) remove the entry from the flush map and disable the alarm
        // 2) handle the new prefixes and replay any cached data messages.
        flushMap.remove(streamID);
        entry.resend.cancel();

        StreamSet streamSet = getStreamSetForMessage(cMsg);

        if(streamSet == null)
        {
          //check that we don't already have a streamSet for this source, because there
          // should only be the one at any one time (except for links, see below...)
          SIBUuid8 sourceMEUuid = cMsg.getGuaranteedSourceMessagingEngineUUID();
          if(sourceMap.containsValue(sourceMEUuid))
          {
            //if we do, try to remove it
            Iterator<SIBUuid12> itr = sourceMap.keySet().iterator();
            while(itr.hasNext())
            {
              SIBUuid12 sid = itr.next();
              SIBUuid8 uuid = sourceMap.get(sid);
              if(sourceMEUuid.equals(uuid))
              {
                // 538529
                // If this is a link it is possible to have multiple streams of messages
                // coming in from the source ME concurrently. We have one for all point-to-point
                // messages and one per topicspace that is sending messages to us.
                // Ideally we need to check with the source before we flush any of our existing
                // streams, as they may still be valid. We would do this by asking the sender if
                // they are flushed (commented out code below). Unfortunately we can't do that because
                // the sender (the other end of the link) may not be the source of the messages
                // so it's not guaranteed to actually know about this stream even if it still
                // exists (for example the ME's just been restarted and lost the non-persistent
                // state for this stream). So, instead we simply keep all streams.
                // TODO This isn't ideal so maybe we can fix it in the future 
                if(destination.isLink())
                {
                  if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(tc, "WARNING: Existing Link stream, " + sid + ", not flushed");
                  
//                  StreamSet existingStreamSet = (StreamSet)streamSets.get(sid);
//
//                  // Create and store the new request record
//                  long reqID = messageProcessor.nextTick();
//                  FlushQueryRecord newEntry = new FlushQueryRecord(sourceMEUuid,
//                                               existingStreamSet.getDestUuid(),
//                                               existingStreamSet.getBusUuid(),
//                                               null,
//                                               reqID);
//                  flushMap.put(sid, newEntry);
//
//                  // Create and send the query
//                  upControl.sendAreYouFlushedMessage(sourceMEUuid,
//                                                     existingStreamSet.getDestUuid(),
//                                                     existingStreamSet.getBusUuid(),
//                                                     reqID,
//                                                     sid);
//
//                  // Start the alarm.  The context for the alarm is the stream id, which
//                  // we can use to look up the FlushQueryRecord if the alarm expires.
//                  newEntry.resend = am.create(GDConfig.FLUSH_QUERY_INTERVAL, this, sid);
                }
                // If we're not a link we only ever expect a single streamSet to be in use
                // by the source at any one time, so flush any that we already have.
                else
                {
                  flush(sid);
                  //there should only ever be at most one other streamSet found
                  //so stop looking if we found one.
                  break;
                }
              }
            }
          }
          
          // If this is a link, get the actual target destination 
          String linkTarget = SIMPConstants.PTOP_TARGET_STREAM;
          JsDestinationAddress routingDest = cMsg.getRoutingDestination();
          if (destination.isLink() &&  routingDest!= null)
          {
            // get the destination and check if it is a topicspace
            DestinationHandler dest = 
              destination.getDestinationManager().
                getDestinationInternal(routingDest.getDestinationName(),
                                       routingDest.getBusName(), true);
            if (dest!=null && dest.isPubSub())
              linkTarget = routingDest.getDestinationName();
          }           
          
          //create a new streamSet
          SIBUuid8 busId = cMsg.getGuaranteedCrossBusSourceBusUUID();
          if( busId == null)
          {
            busId = messageProcessor.getMessagingEngineBusUuid();
          }
          streamSet = addNewStreamSet(streamID,
                                      sourceMEUuid,
                                      cMsg.getGuaranteedTargetDestinationDefinitionUUID(),
                                      busId,
                                      linkTarget);
          //set all the completed prefixes
          long[] completedPrefixes = cMsg.getCompletedPrefixTicks();
          int[] priority  = cMsg.getCompletedPrefixPriority();
          int[] reliability = cMsg.getCompletedPrefixQOS();
          for(int i=0;i<completedPrefixes.length;i++)
          {
            streamSet.setPersistentData(priority[i],
                                                Reliability.getReliability(reliability[i]),
                                                completedPrefixes[i]);
          }
        }
        // Now replay any cached messages
        for(int i=0; i<entry.cacheIndex; i++)
        {
          handleMessage(entry.cache[i]);
        }
      }
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "handleNotFlushedMessage");
  }
1179731
private void handleNewStreamID(MessageItem msgItem) throws SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "handleNewStreamID", new Object[] { msgItem });

    JsMessage jsMsg = msgItem.getMessage();

    handleNewStreamID(jsMsg, msgItem);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "handleNewStreamID");
  }
329278
void handleService(KNXnetIPHeader h, byte[] data, int offset)
		throws KNXFormatException
	{
		final int svc = h.getServiceType();
		if (h.getVersion() != KNXNETIP_VERSION_10)
			close(ConnectionCloseEvent.INTERNAL, "protocol version changed",
				LogLevel.ERROR, null);
		else if (svc == KNXnetIPHeader.ROUTING_IND) {
			final RoutingIndication ind = new RoutingIndication(data, offset,
				h.getTotalLength() - h.getStructLength());
			fireFrameReceived(ind.getCEMI());
		}
		else if (svc == KNXnetIPHeader.ROUTING_LOST_MSG) {
			final RoutingLostMessage lost = new RoutingLostMessage(data, offset);
			fireLostMessage(lost);
		}
		else
			logger.warn("received unknown frame (service type 0x"
				+ Integer.toHexString(svc) + ") - ignored");
	}
1052185
@Override
    public void handle(RequestContext context, AccessDeniedException e) throws SecurityProviderException, IOException {
        saveException(context, e);

        if (StringUtils.isNotEmpty(getErrorPageUrl())) {
            forwardToErrorPage(context);
        } else {
            sendError(e, context);
        }
    }
780690
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("Handling HttpServletRequest {}", request);
		response.setContentType(contentType);
		OutputStream output = response.getOutputStream();
		InputStream input = getRequestStream(request);
		int result = ErrorResolver.JsonError.PARSE_ERROR.code;
		int contentLength = 0;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
			result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

			contentLength = byteOutput.size();
		} catch (Throwable t) {
			if (StreamEndedException.class.isInstance(t)) {
				logger.debug("Bad request: empty contents!");
			} else {
				logger.error(t.getMessage(), t);
			}
		}
		int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
				: httpStatusCodeProvider.getHttpStatusCode(result);
		response.setStatus(httpStatusCode);
		response.setContentLength(contentLength);
		byteOutput.writeTo(output);
		output.flush();
	}
415333
@Override
    public void handleRequest(HttpInboundConnection hic, HttpServletRequest request, HttpServletResponse response) {
        Http2InboundConnection h2ic = (Http2InboundConnection) hic;
        H2UpgradeHandlerWrapper h2uh = null;
        try {
            h2uh = request.upgrade(H2UpgradeHandlerWrapper.class);
        } catch (IOException e) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: user configurator threw an IOException. Exception message: " + e.getMessage());
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;

        } catch (ServletException e) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: user configurator threw a ServletException. Exception message: " + e.getMessage());
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        if (h2uh != null) {
            h2uh.init(new H2UpgradeHandler());
        }
        
        // create a map of the headers to pass to the transport code
        Map<String, String> headers = new HashMap<String, String>();
        HttpServletRequest hsrt = (HttpServletRequest) request;
        Enumeration<String> headerNames = hsrt.getHeaderNames();
        
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = hsrt.getHeader(key);
            headers.put(key, value);
        }
        boolean upgraded = h2ic.handleHTTP2UpgradeRequest(headers);
        if (!upgraded) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: http2 connection initialization failed");
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
821421
@Override
  public void upgrade(Object protocol)
  {
    Objects.requireNonNull(protocol);

    if (protocol instanceof ServiceWebSocket) {
      ServiceWebSocket<?,?> webSocket = (ServiceWebSocket<?,?>) protocol;

      upgradeWebSocket(webSocket);
    }
    else {
      throw new IllegalArgumentException(protocol.toString());
    }
  }
387774
private void configureHttp2UpgradePipeline(ChannelPipeline pipeline, HttpClientCodec sourceCodec,
                                               TargetHandler targetHandler) {
        pipeline.addLast(sourceCodec);
        addCommonHandlers(pipeline);
        Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(http2ConnectionHandler);
        HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec,
                Integer.MAX_VALUE);
        pipeline.addLast(Constants.HTTP2_UPGRADE_HANDLER, upgradeHandler);
        pipeline.addLast(Constants.TARGET_HANDLER, targetHandler);
    }
712454
protected boolean isWebSocketsUpgradeRequest(HttpRequest request) {
        String connectionHeader = request.getHeader( Names.CONNECTION );
        String upgradeHeader = request.getHeader( Names.UPGRADE );

        if (connectionHeader == null || upgradeHeader == null) {
            return false;
        }

        if (connectionHeader.trim().toLowerCase().contains( Values.UPGRADE.toLowerCase() )) {
            if (upgradeHeader.trim().equalsIgnoreCase( Values.WEBSOCKET )) {
                return true;
            }
        }

        return false;
    }
1069592
private void handleResponseFailure(long requestId, Throwable t) {
    ContextualFuture future = responseFutures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.completeExceptionally(t));
    }
  }