Sends a continue response using blocking IO

@param exchange The exchange
777928
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException {
        if (!exchange.isResponseChannelAvailable()) {
            throw UndertowMessages.MESSAGES.cannotSendContinueResponse();
        }
        if(exchange.getAttachment(ALREADY_SENT) != null) {
            return;
        }
        HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange);
        exchange.putAttachment(ALREADY_SENT, true);
        newExchange.setStatusCode(StatusCodes.CONTINUE);
        newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
        newExchange.startBlocking();
        newExchange.getOutputStream().close();
        newExchange.getInputStream().close();
    }
1161279
private void endRequest(HttpServerExchange exchange) {
        exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
        
        Server.headers()
            .entrySet()
            .stream()
            .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
            .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
        
        exchange.endExchange();
    }
551578
def _handle_continue(self, node, scope, ctxt, stream):
        
        self._dlog("handling continue")
        raise errors.InterpContinue()
143998
private void processExchange(final int idx, final HTTPExchange exch) {
        assertUnlocked();

        HTTPResponse resp;
        AbstractBody body;
        int respCode;
        try {
            if (LOG.isLoggable(Level.FINEST))
                LOG.finest(
                    "Thread " + idx + " is sending "
                        + exch.getRequest().getAttribute(Attributes.RID));

            resp = exch.getHTTPResponse();
            body = resp.getBody();
            respCode = resp.getHTTPStatus();

            if (LOG.isLoggable(Level.FINEST)) {
                String respRid = body.getAttribute(Attributes.RID);
                if (respRid == null)
                    respRid = exch.getRequest().getAttribute(Attributes.RID);
                LOG.finest(
                    "Thread " + idx + " received response"
                        + " for RID: " + respRid
                        + " code: " + respCode
                        + " ACK: " + body.getAttribute(Attributes.ACK));
            }
        } catch (BOSHException boshx) {
            LOG.log(Level.FINEST, "Could not obtain response", boshx);
            dispose(boshx);
            return;
        } catch (InterruptedException intx) {
            LOG.log(Level.FINEST, INTERRUPTED, intx);
            dispose(intx);
            return;
        }
        fireResponseReceived(body);

        // Process the message with the current session state
        AbstractBody req = exch.getRequest();
        CMSessionParams params;
        List<HTTPExchange> toResend = null;
        lock.lock();
        try {
            if (!isWorking()) {
                lock.unlock();
                return;
            }
            
            // Check for session creation response info, if needed
            if (cmParams == null) {
                cmParams = CMSessionParams.fromSessionInit(req, body);

                // Adjust number of request processors based on REQ value
                adjustRequestProcessorsPool();

                // The following call handles the lock. It's not an escape.
                fireConnectionEstablished();
            }
            params = cmParams;

            checkForTerminalBindingConditions(body, respCode);
            if (isTermination(body)) {
                // Explicit termination
                lock.unlock();
                dispose(null);
                return;
            }

            // FIXME this may not work with more than 1 RequestProcessor
            if (isRecoverableBindingCondition(body)) {
                // Retransmit outstanding requests
                if (toResend == null) {
                    toResend = new ArrayList<HTTPExchange>(exchanges.size());
                }
                for (HTTPExchange exchange : exchanges) {
                    HTTPExchange resendExch =
                            new HTTPExchange(exchange.getRequest());
                    toResend.add(resendExch);
                }
                for (HTTPExchange exchange : toResend) {
                    exchanges.add(exchange);
                }
            } else {
                // Process message as normal
                processRequestAcknowledgements(req, body);
                processResponseAcknowledgementData(req);
                HTTPExchange resendExch =
                        processResponseAcknowledgementReport(body);
                if (resendExch != null && toResend == null) {
                    toResend = new ArrayList<HTTPExchange>(1);
                    toResend.add(resendExch);
                    exchanges.add(resendExch);
                }
            }
        } catch (BOSHException boshx) {
            LOG.log(Level.FINEST, "Could not process response", boshx);
            lock.unlock();
            dispose(boshx);
            return;
        } finally {
            if (lock.isHeldByCurrentThread()) {
                try {
                    exchanges.remove(exch);
                    if (exchanges.isEmpty()) {
                        scheduleEmptyRequest(processPauseRequest(req));
                    }
                    notFull.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }

        if (toResend != null) {
            for (HTTPExchange resend : toResend) {
                HTTPResponse response =
                        httpSender.send(params, resend.getRequest());
                resend.setHTTPResponse(response);
                fireRequestSent(resend.getRequest());
            }
        }
    }
832838
public function send($exchange, $routing_key, $message, $type = self::TYPE_TOPIC)
    {
        $message = $this->prepareMessage($message);
        if ($type == self::TYPE_TOPIC) {
            $this->channel->exchange_declare($exchange, $type, false, true, false);
        }
        $this->channel->basic_publish($message, $exchange, $routing_key);
    }
174917
public void handleDirectRequest(HttpServerExchange exchange) {
        Log.Info(this,"direct link path:"+exchange.getRelativePath());
        exchange.setResponseCode(200);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html; charset=utf-8");
        exchange.getResponseSender().send( "Hello there, "+exchange.getRequestPath() );
    }
1239029
public function ask($exchange, $routing_key, $message, $timeout)
    {
        list ($queueName) = $this->channel->queue_declare('', false, false, true, false);
        $message = $this->prepareMessage($message, [
            'reply_to' => $queueName,
        ]);
        // queue name must be used for answer's routing key
        $this->channel->queue_bind($queueName, $exchange, $queueName);

        $response = null;
        $callback = function(AMQPMessage $answer) use ($message, &$response) {
            $response = $answer->body;
        };

        $this->channel->basic_consume($queueName, '', false, false, false, false, $callback);
        $this->channel->basic_publish($message, $exchange, $routing_key);
        while (!$response) {
            // exception will be thrown on timeout
            $this->channel->wait(null, false, $timeout);
        }
        return $response;
    }
153769
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {

        // handle request header
        Map<String, Object> requestHeaderMap = (Map<String, Object>)config.get(REQUEST);
        if(requestHeaderMap != null) {
            List<String> requestHeaderRemove = (List<String>)requestHeaderMap.get(REMOVE);
            if(requestHeaderRemove != null) {
                requestHeaderRemove.forEach(s -> exchange.getRequestHeaders().remove(s));
            }
            Map<String, String> requestHeaderUpdate = (Map<String, String>)requestHeaderMap.get(UPDATE);
            if(requestHeaderUpdate != null) {
                requestHeaderUpdate.forEach((k, v) -> exchange.getRequestHeaders().put(new HttpString(k), v));
            }
        }

        // handle response header
        Map<String, Object> responseHeaderMap = (Map<String, Object>)config.get(RESPONSE);
        if(responseHeaderMap != null) {
            List<String> responseHeaderRemove = (List<String>)responseHeaderMap.get(REMOVE);
            if(responseHeaderRemove != null) {
                responseHeaderRemove.forEach(s -> exchange.getResponseHeaders().remove(s));
            }
            Map<String, String> responseHeaderUpdate = (Map<String, String>)responseHeaderMap.get(UPDATE);
            if(responseHeaderUpdate != null) {
                responseHeaderUpdate.forEach((k, v) -> exchange.getResponseHeaders().put(new HttpString(k), v));
            }
        }
        Handler.next(exchange, next);
    }
288933
@Override
    public void sendResponse(StoreStats performanceStats,
                             boolean isFromLocalZone,
                             long startTimeInMs) throws Exception {

        ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(this.responseValue.length);
        responseContent.writeBytes(responseValue);

        // 1. Create the Response object
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

        // 2. Set the right headers
        response.setHeader(CONTENT_TYPE, "binary");
        response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

        // 3. Copy the data into the payload
        response.setContent(responseContent);
        response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

        if(logger.isDebugEnabled()) {
            logger.debug("Response = " + response);
        }

        // Write the response to the Netty Channel
        this.messageEvent.getChannel().write(response);

        if(performanceStats != null && isFromLocalZone) {
            recordStats(performanceStats, startTimeInMs, Tracked.GET);
        }
    }
1007298
@SuppressWarnings("PMD.ExceptionAsFlowControl")
  public HttpResponse send() throws IOException {
    HttpResponse response = null;
    for (int attempt = 1; attempt <= numAttempts; ++attempt) {
      entry.withAttempt(attempt);
      try {
        response = sendImpl();
        int s = response.status();
        if (s == 429 || s == 503) {
          // Request is getting throttled, exponentially back off
          // - 429 client sending too many requests
          // - 503 server unavailable
          try {
            long delay = initialRetryDelay << (attempt - 1);
            LOGGER.debug("request throttled, delaying for {}ms: {} {}", delay, method, uri);
            Thread.sleep(delay);
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("request failed " + method + " " + uri, e);
          }
        } else if (s < 500) {
          // 4xx errors other than 429 are not considered retriable, so for anything
          // less than 500 just return the response to the user
          return response;
        }
      } catch (IOException e) {
        // All exceptions are considered retriable. Some like UnknownHostException are
        // debatable, but we have seen them in some cases if there is a high latency for
        // DNS lookups. So for now assume all exceptions are transient issues.
        if (attempt == numAttempts) {
          throw e;
        } else {
          LOGGER.warn("attempt {} of {} failed: {} {}", attempt, numAttempts, method, uri);
        }
      }
    }

    if (response == null) {
      // Should not get here
      throw new IOException("request failed " + method + " " + uri);
    }
    return response;
  }
1161666
@Override
   public Object invoke(Exchange exchange, Object o)
   {
      BindingOperationInfo bop = exchange.getBindingOperationInfo();
      MethodDispatcher md = (MethodDispatcher) exchange.getService().get(MethodDispatcher.class.getName());
      List<Object> params = null;
      if (o instanceof List) {
         params = CastUtils.cast((List<?>) o);
      } else if (o != null) {
         params = new MessageContentsList(o);
      }
      final Object tb = (factory == null) ? targetBean : this.getServiceObject(exchange);
      final Method method = (bop == null) ? null : md.getMethod(bop);
      if (method == null)
      {
         throw Messages.MESSAGES.missingBindingOpeartionAndDispatchedMethod();
      }
      //performance optimization, adjustMethodAndParams currently looks for @UseAsyncMethod (which is expensive) and only performs actions if it's found
      final Method fm = checkForUseAsyncMethod ? adjustMethodAndParams(md.getMethod(bop), exchange, params, tb.getClass()) : method;
      return invoke(exchange, tb, fm, params);
   }
598903
static void sendResponse(final HttpServerExchange exchange, final String response) {
        exchange.setStatusCode(StatusCodes.OK);
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
        final Sender sender = exchange.getResponseSender();
        UndertowLogger.ROOT_LOGGER.mcmpSendingResponse(exchange.getSourceAddress(), exchange.getStatusCode(), exchange.getResponseHeaders(), response);
        sender.send(response);
    }
754408
public void send(final byte[] frame, final boolean waitForCon)
		throws KNXPortClosedException, KNXAckTimeoutException, InterruptedException
	{
		final boolean group = (frame[3] & 0x80) == 0x80;
		KNXAddress dst = null;
		if (group) {
			dst = new GroupAddress(new byte[] { frame[6], frame[7] });
			sending.add(dst);
		}

		try {
			final byte[] data = toUartServices(cEmiToTP1(frame));
			if (logger.isTraceEnabled())
				logger.trace("create UART services {}", DataUnitBuilder.toHex(data, " "));
			req = frame.clone();
			final long start = System.nanoTime();
			synchronized (enterIdleLock) {
				while (!idle)
					enterIdleLock.wait();
			}
			logger.trace("UART ready for sending after {} us", (System.nanoTime() - start) / 1000);

			logger.debug("write UART services, {}", (waitForCon ? "waiting for .con" : "non-blocking"));
			os.write(data);
			state = ConPending;
			if (!waitForCon)
				return;
			if (waitForCon())
				return;
			throw new KNXAckTimeoutException("no ACK for L-Data.con");
		}
		catch (final InterruptedIOException e) {
			throw new InterruptedException(e.getMessage());
		}
		catch (final IOException e) {
			close();
			throw new KNXPortClosedException("I/O error", portId, e);
		}
		finally {
			req = null;
			sending.remove(dst);
		}
	}
323674
@Override
    public void dumpResponse(Map<String, Object> result) {
        this.statusCodeResult = String.valueOf(exchange.getStatusCode());
        this.putDumpInfoTo(result);
    }
789594
Exchange newExchange(Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    synchronized (connectionPool) {
      if (noMoreExchanges) {
        throw new IllegalStateException("released");
      }
      if (exchange != null) {
        throw new IllegalStateException("cannot make a new request because the previous response "
            + "is still open: please call response.close()");
      }
    }

    ExchangeCodec codec = exchangeFinder.find(client, chain, doExtensiveHealthChecks);
    Exchange result = new Exchange(this, call, eventListener, exchangeFinder, codec);

    synchronized (connectionPool) {
      this.exchange = result;
      this.exchangeRequestDone = false;
      this.exchangeResponseDone = false;
      return result;
    }
  }
494956
void processCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException {
        if (exchange.getRequestPath().equals("*") || exchange.getRequestPath().endsWith("/*")) {
            processNodeCommand(exchange, requestData, action);
        } else {
            processAppCommand(exchange, requestData, action);
        }
    }
853845
@Override
    public void process(Exchange exchange) throws Exception {
        log.debug(exchange.toString());

        if (pin instanceof GPIOPin) {

            GPIOAction messageAction = exchange.getIn().getHeader(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION,
                    getEndpoint().getAction(), GPIOAction.class);

            if (messageAction != null) {
                switch (messageAction) {
                case HIGH:
                    setValue(true);
                    break;
                case LOW:
                    setValue(false);
                    break;
                case TOGGLE:
                    setValue(!pin.getValue());
                    break;
                case BLINK:
                    pool.submit(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(getEndpoint().getDelay());
                                pin.setValue(!pin.getValue());
                                Thread.sleep(getEndpoint().getDuration());
                                pin.setValue(!pin.getValue());
                            } catch (Exception e) {
                                log.error("Thread interruption into BLINK sequence", e);
                            }
                        }
                    });

                    break;
                default:
                    break;
                }
            } else {
                if (pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() != null) {
                    setValue(exchange.getIn().getBody(Boolean.class));
                } else if ((pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() == null)
                        || pin.getDirection() == GPIOPinConfig.DIR_INPUT_ONLY) {
                    exchange.getIn().setBody(pin.getValue(), Boolean.class);
                    exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_PIN, pin.getDescriptor().getID());
                    exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_NAME, pin.getDescriptor().getName());
                    exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_TIMESTAMP, System.currentTimeMillis());

                }
            }
        }
    }