Convert the incoming REST request into the correct
Fcrepo header fields.

@param exchange the current message exchange
966975
public void process(final Exchange exchange) throws Exception {
        final Message in = exchange.getIn();

        final String contentType = in.getHeader(CONTENT_TYPE, "", String.class);
        final String body = in.getBody(String.class);
        final Set<String> endpoints = new HashSet<>();

        for (final String s : in.getHeader(REINDEXING_RECIPIENTS, "", String.class).split(",")) {
            endpoints.add(s.trim());
        }

        if (contentType.equals("application/json") && body != null && !body.trim().isEmpty()) {
            try {
                final JsonNode root = MAPPER.readTree(body);
                final Iterator<JsonNode> ite = root.elements();
                while (ite.hasNext()) {
                    final JsonNode n = ite.next();
                    endpoints.add(n.asText());
                }
            } catch (JsonProcessingException e) {
                LOGGER.debug("Invalid JSON", e);
                in.setHeader(HTTP_RESPONSE_CODE, BAD_REQUEST);
                in.setBody("Invalid JSON");
            }
        }
        in.setHeader(REINDEXING_RECIPIENTS, join(",", endpoints));
    }
1054897
protected final void performUpgrade(final WebSocketHttpExchange exchange, final byte[] data) {
        exchange.setResponseHeader(Headers.CONTENT_LENGTH_STRING, String.valueOf(data.length));
        exchange.setResponseHeader(Headers.UPGRADE_STRING, "WebSocket");
        exchange.setResponseHeader(Headers.CONNECTION_STRING, "Upgrade");
        upgradeChannel(exchange, data);
    }
282077
private void dispatchRequest(final HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final ServletChain servletChain, final DispatcherType dispatcherType) throws Exception {
        HttpHandler next=null;
        try{
            //lets get access of superclass private fields using reflection:
            Field nextField = ServletInitialHandler.class.getDeclaredField("next");
            nextField.setAccessible(true);
            next = (HttpHandler)nextField.get(this);
            nextField.setAccessible(false);
        }catch(NoSuchFieldException | IllegalAccessException e){
            throw new ServletException(e);
        }

        servletRequestContext.setDispatcherType(dispatcherType);
        servletRequestContext.setCurrentServlet(servletChain);
        if (dispatcherType == DispatcherType.REQUEST || dispatcherType == DispatcherType.ASYNC) {
            super.handleFirstRequest(exchange, servletChain, servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse());
        } else {
            next.handleRequest(exchange);
        }
    }
1017916
public static boolean checkOrigin(ServerEndpointConfig config, WebSocketHttpExchange exchange) {
        ServerEndpointConfig.Configurator c = config.getConfigurator();
        return c.checkOrigin(exchange.getRequestHeader(Headers.ORIGIN_STRING));
    }
433740
public void insertAndFireAll(Exchange exchange) {
        final Message in = exchange.getIn();
        final Object body = in.getBody();

        BatchExecutionCommandImpl command = new BatchExecutionCommandImpl();
        final List<GenericCommand<?>> commands = command.getCommands();
        commands.add(new InsertObjectCommand(body, "obj1"));
        commands.add(new FireAllRulesCommand());

        in.setBody(command);
    }
611514
public function deferExchangeMessage(ExchangeEnvelope $deferredExchange, $endpointURI = null)
    {
        $exchange = new Exchange($deferredExchange);

        if (!$endpointURI) {
            $oldExchange = $deferredExchange->getBody();
            $endpointURI = $oldExchange->getHeader(Exchange::HEADER_FROM);
        }

        $endpoint = $this->getEndpointFactory()->createEndpoint($endpointURI, EndpointFactory::MODE_PRODUCE);

        $endpoint->produce($exchange);
    }
647334
@SuppressWarnings("rawtypes")
    protected Form getForm(HttpServerExchange exchange) throws IOException {
        final Form form = Application.getInstance(Form.class);
        if (RequestUtils.isPostPutPatch(exchange)) {
            final Builder builder = FormParserFactory.builder();
            builder.setDefaultCharset(StandardCharsets.UTF_8.name());
            try (final FormDataParser formDataParser = builder.build().createParser(exchange)) {
                if (formDataParser != null) {
                    exchange.startBlocking();
                    final FormData formData = formDataParser.parseBlocking();
                    for (String data : formData) {
                        Deque<FormValue> deque = formData.get(data);
                        if (deque != null) {
                            FormValue formValue = deque.element();
                            if (formValue != null) {
                                if (formValue.isFileItem() && formValue.getFileItem().getFile() != null) {
                                    form.addFile(Files.newInputStream(formValue.getFileItem().getFile()));
                                } else {
                                    if (data.contains("[]")) {
                                        String key = StringUtils.replace(data, "[]", "");
                                        for (Iterator iterator = deque.iterator(); iterator.hasNext();)  {
                                            form.addValueList(new HttpString(key).toString(), ((FormValue) iterator.next()).getValue());
                                        }
                                    } else {
                                        form.addValue(new HttpString(data).toString(), formValue.getValue());
                                    }
                                }    
                            }
                        }
                    }
                }
            }
            
            form.setSubmitted(true);
        }

        return form;
    }
593901
public static function resolveURIParams(Exchange $exchange, $uri)
    {
        preg_match_all('/\\{([^{}]+)\\}/', $uri, $matches);
        $params = $matches[1];
        $headers = $exchange->getHeaders();

        if (!empty($params)) {
            foreach ($params as $param) {
                if (array_key_exists($param, $headers)) {
                    $uri = str_replace('{'.$param.'}', $headers[$param], $uri);
                } else {
                    throw new \RuntimeException(
                        "Missing exchange header \"$param\" required to resolve the uri \"$uri\""
                    );
                }
            }
        }

        return $uri;
    }
156852
private void endRequest(HttpServerExchange exchange, String redirect) {
        exchange.setStatusCode(StatusCodes.FOUND);
        
        Server.headers()
            .entrySet()
            .stream()
            .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
            .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
        
        exchange.getResponseHeaders().put(Header.LOCATION.toHttpString(), redirect);
        exchange.endExchange();
    }
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();
    }
314242
void recoverExchange(String exchangeName, ResourceDeclaration exchangeDeclaration)
      throws Exception {
    try {
      log.info("Recovering exchange {} via {}", exchangeName, this);
      exchangeDeclaration.invoke(getRecoveryChannel());
    } catch (Exception e) {
      log.error("Failed to recover exchange {} via {}", exchangeName, this, e);
      if (throwOnRecoveryFailure() || Exceptions.isCausedByConnectionClosure(e))
        throw e;
    }
  }
1239903
void handleInitialRequest(HttpServerExchange initial, Http2Channel channel, byte[] data) {

        //we have a request
        Http2HeadersStreamSinkChannel sink = channel.createInitialUpgradeResponseStream();
        final Http2ServerConnection connection = new Http2ServerConnection(channel, sink, undertowOptions, bufferSize, rootHandler);


        HeaderMap requestHeaders = new HeaderMap();
        for(HeaderValues hv : initial.getRequestHeaders()) {
            requestHeaders.putAll(hv.getHeaderName(), hv);
        }
        final HttpServerExchange exchange = new HttpServerExchange(connection, requestHeaders, sink.getHeaders(), maxEntitySize);
        if(initial.getRequestHeaders().contains(Headers.EXPECT)) {
            HttpContinue.markContinueResponseSent(exchange);
        }
        if(initial.getAttachment(HttpAttachments.REQUEST_TRAILERS) != null) {
            exchange.putAttachment(HttpAttachments.REQUEST_TRAILERS, initial.getAttachment(HttpAttachments.REQUEST_TRAILERS));
        }
        Connectors.setRequestStartTime(initial, exchange);
        connection.setExchange(exchange);
        exchange.setRequestScheme(initial.getRequestScheme());
        exchange.setRequestMethod(initial.getRequestMethod());
        exchange.setQueryString(initial.getQueryString());
        if(data != null) {
            Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(data)));
        } else {
            Connectors.terminateRequest(exchange);
        }
        String uri = exchange.getQueryString().isEmpty() ? initial.getRequestURI() : initial.getRequestURI() + '?' + exchange.getQueryString();
        try {
            Connectors.setExchangeRequestPath(exchange, uri, encoding, decode, allowEncodingSlash, decodeBuffer, maxParameters);
        } catch (ParameterLimitException e) {
            exchange.setStatusCode(StatusCodes.BAD_REQUEST);
            exchange.endExchange();
            return;
        }


        handleCommonSetup(sink, exchange, connection);
        Connectors.executeRootHandler(rootHandler, exchange);
    }
1084906
protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
    {
        $itinerary = $exchange->getItinerary();

        if ($itinerary->getProcessorIdsCount() > 0) {
            $exchangeBackup = clone $exchange;

            // Take the next processor
            $processorId = $itinerary->shiftProcessorId();
            if (!$this->container->has($processorId)) {
                throw new \RuntimeException("Processor with $processorId not found in container.");
            }
            $processor = $this->container->get($processorId);
            if (!$processor instanceof ProcessorInterface) {
                throw new \RuntimeException('Processors must implement ProcessorInterface.');
            }

            // Prepend this processor
            $itinerary->unShiftProcessorId($this->getId());

            try {
                $processor->process($exchange);
            } catch (ProcessingException $exception) {
                $originalException = $exception->getOriginalException();

                // We try to catch the exception
                foreach ($this->catches as $catch) {
                    if ($this->evaluator->evaluateWithExchange($catch->getCondition(), $exchange, $originalException)) {
                        $exchange->setIn($exchangeBackup->getIn());
                        $exchange->setOut(null);
                        $exchange->setItinerary($catch->getItinerary());
                        if ($this->finallyItinerary) {
                            $exchange->getItinerary()->append($this->finallyItinerary);
                        }

                        return;
                    }
                }

                // If it's not catch, we just let go, if the exchange is retried, we will come to this processor again
                throw $originalException;
            }
        } elseif ($this->finallyItinerary) {
            $exchange->getItinerary()->prepend($this->finallyItinerary);
        }
    }
971494
def exchange_reference(root_url, service, version):
    """"""
    root_url = root_url.rstrip('/')
    if root_url == OLD_ROOT_URL:
        return 'https://references.taskcluster.net/{}/{}/exchanges.json'.format(service, version)
    else:
        return '{}/references/{}/{}/exchanges.json'.format(root_url, service, version)
875860
def handle_return(header, message)
      begin
        to = if header.exchange && !header.exchange.empty? then header.exchange else header.routing_key end
        reason = header.reply_text
        callback = @options[:return_message_callback]
        logger.__send__(callback ? :debug : :info, "RETURN #{@alias} for #{to} because #{reason}")
        callback.call(@identity, to, reason, message) if callback
      rescue Exception => e
        logger.exception("Failed return #{header.inspect} of message from broker #{@alias}", e, :trace)
        @exception_stats.track("return", e)
      end
      true
    end
490973
public static void setExchangeRequestPath(final HttpServerExchange exchange, final String encodedPath, final String charset, boolean decode, final boolean allowEncodedSlash, StringBuilder decodeBuffer, int maxParameters) throws ParameterLimitException {
        boolean requiresDecode = false;
        for (int i = 0; i < encodedPath.length(); ++i) {
            char c = encodedPath.charAt(i);
            if (c == '?') {
                String part;
                String encodedPart = encodedPath.substring(0, i);
                if (requiresDecode) {
                    part = URLUtils.decode(encodedPart, charset, allowEncodedSlash,false, decodeBuffer);
                } else {
                    part = encodedPart;
                }
                exchange.setRequestPath(part);
                exchange.setRelativePath(part);
                exchange.setRequestURI(encodedPart);
                final String qs = encodedPath.substring(i + 1);
                exchange.setQueryString(qs);
                URLUtils.parseQueryString(qs, exchange, charset, decode, maxParameters);
                return;
            } else if(c == ';') {
                String part;
                String encodedPart = encodedPath.substring(0, i);
                if (requiresDecode) {
                    part = URLUtils.decode(encodedPart, charset, allowEncodedSlash, false, decodeBuffer);
                } else {
                    part = encodedPart;
                }
                exchange.setRequestPath(part);
                exchange.setRelativePath(part);
                for(int j = i; j < encodedPath.length(); ++j) {
                    if (encodedPath.charAt(j) == '?') {
                        exchange.setRequestURI(encodedPath.substring(0, j));
                        String pathParams = encodedPath.substring(i + 1, j);
                        URLUtils.parsePathParams(pathParams, exchange, charset, decode, maxParameters);
                        String qs = encodedPath.substring(j + 1);
                        exchange.setQueryString(qs);
                        URLUtils.parseQueryString(qs, exchange, charset, decode, maxParameters);
                        return;
                    }
                }
                exchange.setRequestURI(encodedPath);
                URLUtils.parsePathParams(encodedPath.substring(i + 1), exchange, charset, decode, maxParameters);
                return;
            } else if(c == '%' || c == '+') {
                requiresDecode = decode;
            }
        }

        String part;
        if (requiresDecode) {
            part = URLUtils.decode(encodedPath, charset, allowEncodedSlash, false, decodeBuffer);
        } else {
            part = encodedPath;
        }
        exchange.setRequestPath(part);
        exchange.setRelativePath(part);
        exchange.setRequestURI(encodedPath);
    }
522300
protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
    {
        if (empty($this->exceptionClass)) {
            throw new \RuntimeException('Exception class not found');
        }

        /** @var ExchangeAwareInterface $exception */
        $exception = new $this->exceptionClass($this->exceptionMessage);

        throw $exception;
    }